File: AttributeAddUsersGroups.php

package info (click to toggle)
simplesamlphp 1.19.7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 42,920 kB
  • sloc: php: 202,044; javascript: 14,867; xml: 2,700; sh: 225; perl: 82; makefile: 70; python: 5
file content (421 lines) | stat: -rw-r--r-- 14,610 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
<?php

namespace SimpleSAML\Module\ldap\Auth\Process;

use SimpleSAML\Logger;
use SimpleSAML\Utils\Arrays;

/**
 * Does a reverse membership lookup on the logged in user,
 * looking for groups it is a member of and adds them to
 * a defined attribute, in DN format.
 *
 * @author Ryan Panning <panman@traileyes.com>
 * @package SimpleSAMLphp
 */
class AttributeAddUsersGroups extends BaseFilter
{
    /**
     * LDAP search filters to be added to the base filters for this authproc-filter.
     * It's an array of key => value pairs that will be translated to (key=value) in the ldap query.
     *
     * @var array
     */
    protected $additional_filters;

    /**
     * A flag whether to escape the additional filter values or not. Defaults to TRUE
     *
     * @var bool
     */
    protected $escape;


    /**
     * This is run when the filter is processed by SimpleSAML.
     * It will attempt to find the current users groups using
     * the best method possible for the LDAP product. The groups
     * are then added to the request attributes.
     *
     * @throws \SimpleSAML\Error\Exception
     * @param $request
     * @return void
     */
    public function process(&$request)
    {
        assert(is_array($request));
        assert(array_key_exists('Attributes', $request));

        // Log the process
        \SimpleSAML\Logger::debug(
            $this->title.'Attempting to get the users groups...'
        );

        $this->additional_filters = $this->config->getArray('additional_filters', []);
        $this->escape = $this->config->getBoolean('escape', true);

        // Reference the attributes, just to make the names shorter
        $attributes = &$request['Attributes'];
        $map = &$this->attribute_map;

        // Get the users groups from LDAP
        $groups = $this->getGroups($attributes);

        // If there are none, do not proceed
        if (empty($groups)) {
            return;
        }

        // Make the array if it is not set already
        if (!isset($attributes[$map['groups']])) {
            $attributes[$map['groups']] = [];
        }

        // Must be an array, else cannot merge groups
        if (!is_array($attributes[$map['groups']])) {
            throw new \SimpleSAML\Error\Exception(
                $this->title.'The group attribute ['.$map['groups'].
                '] is not an array of group DNs. '.$this->var_export($attributes[$map['groups']])
            );
        }

        // Add the users group(s)
        $group_attribute = &$attributes[$map['groups']];
        $group_attribute = array_merge($group_attribute, $groups);
        $group_attribute = array_unique($group_attribute);

        // All done
        \SimpleSAML\Logger::debug(
            $this->title.'Added users groups to the group attribute ['.
            $map['groups'].']: '.implode('; ', $groups)
        );
    }


    /**
     * This section of code was broken out because the child
     * filter AuthorizeByGroup can use this method as well.
     * Based on the LDAP product, it will do an optimized search
     * using the required attribute values from the user to
     * get their group membership, recursively.
     *
     * @throws \SimpleSAML\Error\Exception
     * @param array $attributes
     * @return array
     */
    protected function getGroups($attributes)
    {
        // Log the request
        \SimpleSAML\Logger::debug(
            $this->title.'Checking for groups based on the best method for the LDAP product.'
        );

        // Based on the directory service, search LDAP for groups
        // If any attributes are needed, prepare them before calling search method
        switch ($this->product) {
            case 'ACTIVEDIRECTORY':
                $groups = $this->getGroupsActiveDirectory($attributes);
                break;
            case 'OPENLDAP':
                $groups = $this->getGroupsOpenLdap($attributes);
                break;
            default:
                // Reference the map, just to make the name shorter
                $map = &$this->attribute_map;

                // Log the general search
                \SimpleSAML\Logger::debug(
                    $this->title.'Searching LDAP using the default search method.'
                );

                // Make sure the defined memberOf attribute exists
                if (!isset($attributes[$map['memberof']])) {
                    throw new \SimpleSAML\Error\Exception(
                        $this->title.'The memberof attribute ['.$map['memberof'].
                        '] is not defined in the user\'s Attributes: '.implode(', ', array_keys($attributes))
                    );
                }

                // MemberOf must be an array of group DN's
                if (!is_array($attributes[$map['memberof']])) {
                    throw new \SimpleSAML\Error\Exception(
                        $this->title.'The memberof attribute ['.$map['memberof'].
                        '] is not an array of group DNs. '.$this->var_export($attributes[$map['memberof']])
                    );
                }

                // Search for the users group membership, recursively
                $groups = $this->search($attributes[$map['memberof']]);
        }

        // All done
        \SimpleSAML\Logger::debug(
            $this->title.'User found to be a member of the groups:'.implode('; ', $groups)
        );
        return $groups;
    }


    /**
     * OpenLDAP optimized search
     * using the required attribute values from the user to
     * get their group membership, recursively.
     *
     * @throws \SimpleSAML\Error\Exception
     * @param array $attributes
     * @return array
     */
    protected function getGroupsOpenLdap($attributes)
    {
        // Log the OpenLDAP specific search
        \SimpleSAML\Logger::debug(
            $this->title.'Searching LDAP using OpenLDAP specific method.'
        );

        // Reference the map, just to make the name shorter
        $map = &$this->attribute_map;

        // Print group search string and search for all group names
        $openldap_base = $this->config->getString('ldap.basedn', 'ou=groups,dc=example,dc=com');
        \SimpleSAML\Logger::debug(
            $this->title."Searching for groups in ldap.basedn ".$openldap_base." with filter (".$map['memberof'].
            "=".$attributes[$map['username']][0].") and attributes ".$map['member']
        );

        $groups = [];
        try {
            /* Intention is to filter in 'ou=groups,dc=example,dc=com' for
             * '(memberUid = <value of attribute.username>)' and take only the attributes 'cn' (=name of the group)
             */
            $all_groups = $this->getLdap()->searchformultiple(
                $openldap_base,
                array_merge(
                    [
                        $map['memberof'] => $attributes[$map['username']][0]
                    ],
                    $this->additional_filters
                ),
                [$map['return']]
            );
        } catch (\SimpleSAML\Error\UserNotFound $e) {
            return $groups; // if no groups found return with empty (still just initialized) groups array
        }

        // run through all groups and add each to our groups array
        foreach ($all_groups as $group_entry) {
            $groups[] = $group_entry[$map['return']][0];
        }

        return $groups;
    }


    /**
     * Active Directory optimized search
     * using the required attribute values from the user to
     * get their group membership, recursively.
     *
     * @throws \SimpleSAML\Error\Exception
     * @param array $attributes
     * @return array
     */
    protected function getGroupsActiveDirectory($attributes)
    {
        // Log the AD specific search
        \SimpleSAML\Logger::debug(
            $this->title.'Searching LDAP using ActiveDirectory specific method.'
        );

        // Reference the map, just to make the name shorter
        $map = &$this->attribute_map;

        // Make sure the defined dn attribute exists
        if (!isset($attributes[$map['dn']])) {
            throw new \SimpleSAML\Error\Exception(
                $this->title.'The DN attribute ['.$map['dn'].
                '] is not defined in the user\'s Attributes: '.implode(', ', array_keys($attributes))
            );
        }

        // DN attribute must have a value
        if (!isset($attributes[$map['dn']][0]) || !$attributes[$map['dn']][0]) {
            throw new \SimpleSAML\Error\Exception(
                $this->title.'The DN attribute ['.$map['dn'].
                '] does not have a [0] value defined. '.$this->var_export($attributes[$map['dn']])
            );
        }

        // Pass to the AD specific search
        return $this->searchActiveDirectory($attributes[$map['dn']][0]);
    }

    /**
     * Looks for groups from the list of DN's passed. Also
     * recursively searches groups for further membership.
     * Avoids loops by only searching a DN once. Returns
     * the list of groups found.
     *
     * @param array $memberof
     * @return array
     */
    protected function search($memberof)
    {
        assert(is_array($memberof));

        // Used to determine what DN's have already been searched
        static $searched = [];

        // Init the groups variable
        $groups = [];

        // Shorten the variable name
        $map = &$this->attribute_map;

        // Log the search
        \SimpleSAML\Logger::debug(
            $this->title.'Checking DNs for groups.'.
            ' DNs: '.implode('; ', $memberof).
            ' Attributes: '.$map['memberof'].', '.$map['type'].
            ' Group Type: '.$this->type_map['group']
        );

        // Work out what attributes to get for a group
        $use_group_name = false;
        $get_attributes = [$map['memberof'], $map['type']];
        if (isset($map['name']) && $map['name']) {
            $get_attributes[] = $map['name'];
            $use_group_name = true;
        }

        // Check each DN of the passed memberOf
        foreach ($memberof as $dn) {
            // Avoid infinite loops, only need to check a DN once
            if (isset($searched[$dn])) {
                continue;
            }

            // Track all DN's that are searched
            // Use DN for key as well, isset() is faster than in_[]
            $searched[$dn] = $dn;

            // Query LDAP for the attribute values for the DN
            try {
                $attributes = $this->getLdap()->getAttributes($dn, $get_attributes);
            } catch (\SimpleSAML\Error\AuthSource $e) {
                continue; // DN must not exist, just continue. Logged by the LDAP object
            }

            // Only look for groups
            if (!in_array($this->type_map['group'], $attributes[$map['type']], true)) {
                continue;
            }

            // Add to found groups array
            if ($use_group_name && isset($attributes[$map['name']]) && is_array($attributes[$map['name']])) {
                $groups[] = $attributes[$map['name']][0];
            } else {
                $groups[] = $dn;
            }

            // Recursively search "sub" groups
            if (!empty($attributes[$map['memberof']])) {
                $groups = array_merge($groups, $this->search($attributes[$map['memberof']]));
            }
        }

        // Return only the unique group names
        return array_unique($groups);
    }


    /**
     * Searches LDAP using a ActiveDirectory specific filter,
     * looking for group membership for the users DN. Returns
     * the list of group DNs retrieved.
     *
     * @param string $dn
     * @return array
     */
    protected function searchActiveDirectory($dn)
    {
        assert(is_string($dn) && $dn != '');

        // Shorten the variable name
        $map = &$this->attribute_map;

        // Log the search
        Logger::debug(
            $this->title . 'Searching ActiveDirectory group membership.' .
            ' DN: ' . $dn .
            ' DN Attribute: ' . $map['dn'] .
            ' Return Attribute: ' . $map['return'] .
            ' Member Attribute: ' . $map['member'] .
            ' Type Attribute: ' . $map['type'] .
            ' Type Value: ' . $this->type_map['group'] .
            ' Base: ' . implode('; ', Arrays::arrayize($this->base_dn))
        );

        // AD connections should have this set
        $this->getLdap()->setOption(LDAP_OPT_REFERRALS, 0);

        // Search AD with the specific recursive flag
        try {
            $entries = $this->getLdap()->searchformultiple(
                $this->base_dn,
                array_merge(
                    $this->getLdap()::escape_filter_value(
                        [
                            $map['type'] => $this->type_map['group'],
                            $map['member'] . ':1.2.840.113556.1.4.1941:' => $dn
                        ],
                        false
                    ),
                    $this->additional_filters
                ),
                [$map['return']], // attributes
                [], // binary attributes
                true, // AND
                $this->escape // escape filter values
            );

        // The search may throw an exception if no entries
        // are found, unlikely but possible.
        } catch (\SimpleSAML\Error\UserNotFound $e) {
            return [];
        }

        //Init the groups
        $groups = [];

        // Check each entry..
        foreach ($entries as $entry) {
            // Check for the DN using the original attribute name
            if (isset($entry[$map['return']][0])) {
                $groups[] = $entry[$map['return']][0];
                continue;
            }

            // Sometimes the returned attribute names are lowercase
            if (isset($entry[strtolower($map['return'])][0])) {
                $groups[] = $entry[strtolower($map['return'])][0];
                continue;
            }

            // AD queries also seem to return the objects dn by default
            if (isset($entry['dn'])) {
                $groups[] = $entry['dn'];
                continue;
            }

            // Could not find DN, log and continue
            \SimpleSAML\Logger::notice(
                $this->title . 'The return attribute [' .
                implode(', ', [$map['return'], strtolower($map['return'])]) .
                '] could not be found in the entry. ' . $this->var_export($entry)
            );
        }

        // All done
        return $groups;
    }
}