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

AttributeAddUsersGroups   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 344
Duplicated Lines 0 %

Importance

Changes 9
Bugs 0 Features 0
Metric Value
eloc 160
c 9
b 0
f 0
dl 0
loc 344
rs 10
wmc 26

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A process() 0 50 4
C getGroups() 0 167 10
B search() 0 56 11
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
            if ($entry->hasAttribute($return_attribute)) {
269
                $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

269
                $groups[] = array_pop(/** @scrutinizer ignore-type */ $entry->getAttribute($return_attribute));
Loading history...
270
                continue;
271
            } elseif ($entry->hasAttribute(strtolower($return_attribute))) {
272
                // Some backends return lowercase attributes
273
                $groups[] = array_pop($entry->getAttribute(strtolower($return_attribute)));
0 ignored issues
show
Bug introduced by
$entry->getAttribute(str...wer($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

273
                $groups[] = array_pop(/** @scrutinizer ignore-type */ $entry->getAttribute(strtolower($return_attribute)));
Loading history...
274
                continue;
275
            } elseif ($entry->hasAttribute('dn')) {
276
                // AD queries also seem to return the objects dn by default
277
                $groups[] = array_pop($entry->getAttribute('dn'));
0 ignored issues
show
Bug introduced by
$entry->getAttribute('dn') 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

277
                $groups[] = array_pop(/** @scrutinizer ignore-type */ $entry->getAttribute('dn'));
Loading history...
278
                continue;
279
            }
280
281
            // Could not find DN, log and continue
282
            Logger::notice(sprintf(
283
                '%s : The return attribute [%s] could not be found in the entry. %s',
284
                $this->title,
285
                implode(', ', [$map['return'], strtolower($map['return'], 'dn')]),
0 ignored issues
show
Unused Code introduced by
The call to strtolower() has too many arguments starting with 'dn'. ( Ignorable by Annotation )

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

285
                implode(', ', [$map['return'], /** @scrutinizer ignore-call */ strtolower($map['return'], 'dn')]),

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
286
                $this->varExport($entry),
287
            ));
288
        }
289
290
        // All done
291
        Logger::debug(sprintf(
292
            '%s : User found to be a member of the groups: %s',
293
            implode('; ', $groups),
294
            $this->title,
295
        ));
296
297
        return $groups;
298
    }
299
300
301
    /**
302
     * Looks for groups from the list of DN's passed. Also
303
     * recursively searches groups for further membership.
304
     * Avoids loops by only searching a DN once. Returns
305
     * the list of groups found.
306
     *
307
     * @param array $memberof
308
     * @return array
309
     */
310
    protected function search(array $memberof): array
311
    {
312
        // Used to determine what DN's have already been searched
313
        static $searched = [];
314
315
        // Init the groups variable
316
        $groups = [];
317
318
        // Shorten the variable name
319
        //$map = &$this->attribute_map;
320
321
        // Work out what attributes to get for a group
322
        $use_group_name = false;
323
        $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...
324
        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...
325
            $get_attributes[] = $map['name'];
326
            $use_group_name = true;
327
        }
328
329
        // Check each DN of the passed memberOf
330
        foreach ($memberof as $dn) {
331
            // Avoid infinite loops, only need to check a DN once
332
            if (isset($searched[$dn])) {
333
                continue;
334
            }
335
336
            // Track all DN's that are searched
337
            // Use DN for key as well, isset() is faster than in_array()
338
            $searched[$dn] = $dn;
339
340
            // Query LDAP for the attribute values for the DN
341
            try {
342
                $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

342
                $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...
343
            } catch (Error\AuthSource $e) {
344
                continue; // DN must not exist, just continue. Logged by the LDAP object
345
            }
346
347
            // Only look for groups
348
            if (!in_array($this->type_map['group'], $attributes[$map['type']], true)) {
349
                continue;
350
            }
351
352
            // Add to found groups array
353
            if ($use_group_name && isset($attributes[$map['name']]) && is_array($attributes[$map['name']])) {
354
                $groups[] = $attributes[$map['name']][0];
355
            } else {
356
                $groups[] = $dn;
357
            }
358
359
            // Recursively search "sub" groups
360
            if (!empty($attributes[$map['memberof']])) {
361
                $groups = array_merge($groups, $this->search($attributes[$map['memberof']]));
362
            }
363
        }
364
365
        return $groups;
366
    }
367
}
368