Passed
Push — master ( f275b9...3d5dc7 )
by Tim
02:55
created

Ldap::buildSearchFilter()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 18
rs 9.9666
cc 3
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\ldap\Auth\Source;
6
7
use SimpleSAML\Assert\Assert;
8
use SimpleSAML\Configuration;
9
use SimpleSAML\Error;
10
use SimpleSAML\Module\core\Auth\UserPassBase;
11
use SimpleSAML\Module\ldap\ConnectorFactory;
12
use SimpleSAML\Module\ldap\ConnectorInterface;
13
use Symfony\Component\Ldap\Adapter\ExtLdap\Query;
14
use Symfony\Component\Ldap\Entry;
15
16
use function array_fill_keys;
17
use function array_keys;
18
use function array_map;
19
use function array_values;
20
use function sprintf;
21
use function str_replace;
22
use function var_export;
23
24
/**
25
 * LDAP authentication source.
26
 *
27
 * See the ldap-entry in config-templates/authsources.php for information about
28
 * configuration of this authentication source.
29
 *
30
 * @package simplesamlphp/simplesamlphp-module-ldap
31
 */
32
33
class Ldap extends UserPassBase
34
{
35
    /**
36
     * @var \SimpleSAML\Module\ldap\ConnectorInterface
37
     */
38
    protected ConnectorInterface $connector;
39
40
    /**
41
     * An LDAP configuration object.
42
     */
43
    protected Configuration $ldapConfig;
44
45
46
    /**
47
     * Constructor for this authentication source.
48
     *
49
     * @param array $info  Information about this authentication source.
50
     * @param array $config  Configuration.
51
     */
52
    public function __construct(array $info, array $config)
53
    {
54
        // Call the parent constructor first, as required by the interface
55
        parent::__construct($info, $config);
56
57
        $this->ldapConfig = Configuration::loadFromArray(
58
            $config,
59
            'authsources[' . var_export($this->authId, true) . ']'
60
        );
61
62
        $this->connector = ConnectorFactory::fromAuthSource($this->authId);
63
    }
64
65
66
    /**
67
     * Attempt to log in using the given username and password.
68
     *
69
     * @param string $username  The username the user wrote.
70
     * @param string $password  The password the user wrote.
71
     * @return array  Associative array with the users attributes.
72
     */
73
    protected function login(string $username, string $password): array
74
    {
75
        $searchScope = $this->ldapConfig->getOptionalString('search.scope', Query::SCOPE_SUB);
76
        Assert::oneOf($searchScope, [Query::SCOPE_BASE, Query::SCOPE_ONE, Query::SCOPE_SUB]);
77
78
        $timeout = $this->ldapConfig->getOptionalInteger('timeout', 3);
79
        Assert::natural($timeout);
80
81
        $searchBase = $this->ldapConfig->getArray('search.base');
82
        $options = [
83
            'scope' => $searchScope,
84
            'timeout' => $timeout,
85
        ];
86
87
        $searchEnable = $this->ldapConfig->getOptionalBoolean('search.enable', false);
88
        if ($searchEnable === false) {
89
            $dnPattern = $this->ldapConfig->getString('dnpattern');
90
            $dn = str_replace('%username%', $username, $dnPattern);
91
        } else {
92
            $searchUsername = $this->ldapConfig->getString('search.username');
93
            Assert::notWhitespaceOnly($searchUsername);
94
95
            $searchPassword = $this->ldapConfig->getOptionalString('search.password', null);
96
            Assert::nullOrnotWhitespaceOnly($searchPassword);
97
98
            try {
99
                $this->connector->bind($searchUsername, $searchPassword);
100
            } catch (Error\Error $e) {
101
                throw new Error\Exception("Unable to bind using the configured search.username and search.password.");
102
            }
103
104
            $filter = $this->buildSearchFilter($username);
105
106
            try {
107
                $entry = /** @scrutinizer-ignore-type */$this->connector->search($searchBase, $filter, $options, false);
108
                $dn = $entry->getDn();
109
            } catch (Error\Exception $e) {
110
                throw new Error\Error('WRONGUSERPASS');
111
            }
112
        }
113
114
        $this->connector->bind($dn, $password);
115
116
        $options['scope'] = Query::SCOPE_BASE;
117
        $filter = '(objectClass=*)';
118
119
        $entry = $this->connector->search([$dn], $filter, $options, false);
120
121
        return $this->processAttributes(/** @scrutinizer-ignore-type */$entry);
122
    }
123
124
125
    /**
126
     * Attempt to find a user's attributes given its username.
127
     *
128
     * @param string $username  The username who's attributes we want.
129
     * @return array  Associative array with the users attributes.
130
     */
131
    public function getAttributes(string $username): array
132
    {
133
        $searchUsername = $this->ldapConfig->getString('search.username');
134
        Assert::notWhitespaceOnly($searchUsername);
135
136
        $searchPassword = $this->ldapConfig->getOptionalString('search.password', null);
137
        Assert::nullOrnotWhitespaceOnly($searchPassword);
138
139
        try {
140
            $this->connector->bind($searchUsername, $searchPassword);
141
        } catch (Error\Error $e) {
142
            throw new Error\Exception("Unable to bind using the configured search.username and search.password.");
143
        }
144
145
        $searchEnable = $this->ldapConfig->getOptionalBoolean('search.enable', false);
146
        if ($searchEnable === false) {
147
            $dnPattern = $this->ldapConfig->getString('dnpattern');
148
            $filter = '(' . str_replace('%username%', $username, $dnPattern) . ')';
149
        } else {
150
            $filter = $this->buildSearchFilter($username);
151
        }
152
153
        $searchScope = $this->ldapConfig->getOptionalString('search.scope', Query::SCOPE_SUB);
154
        Assert::oneOf($searchScope, [Query::SCOPE_BASE, Query::SCOPE_ONE, Query::SCOPE_SUB]);
155
156
        $timeout = $this->ldapConfig->getOptionalInteger('timeout', 3);
157
        Assert::natural($timeout);
158
159
        $searchBase = $this->ldapConfig->getArray('search.base');
160
        $options = [
161
            'scope' => $searchScope,
162
            'timeout' => $timeout,
163
        ];
164
165
        try {
166
            /** @var \Symfony\Component\Ldap\Entry $entry */
167
            $entry = $this->connector->search($searchBase, $filter, $options, false);
168
        } catch (Error\Exception $e) {
169
            throw new Error\Error('WRONGUSERPASS');
170
        }
171
172
        return $this->processAttributes($entry);
173
    }
174
175
176
    /**
177
     * @param \Symfony\Component\Ldap\Entry $entry
178
     * @return array
179
     */
180
    private function processAttributes(Entry $entry): array
181
    {
182
        $attributes = $this->ldapConfig->getOptionalValue('attributes', []);
183
        if ($attributes === null) {
184
            $result = $entry->getAttributes();
185
        } else {
186
            Assert::isArray($attributes);
187
            $result = array_intersect_key(
188
                $entry->getAttributes(),
189
                array_fill_keys(array_values($attributes), null)
190
            );
191
        }
192
193
        $binaries = array_intersect(
194
            array_keys($result),
195
            $this->ldapConfig->getOptionalArray('attributes.binary', []),
196
        );
197
        foreach ($binaries as $binary) {
198
            $result[$binary] = array_map('base64_encode', $result[$binary]);
199
        }
200
201
        return $result;
202
    }
203
204
205
    /**
206
     * @param string $username
207
     * @return string
208
     */
209
    private function buildSearchFilter(string $username): string
210
    {
211
        $searchAttributes = $this->ldapConfig->getArray('search.attributes');
212
        /** @psalm-var string|null $searchFilter */
213
        $searchFilter = $this->ldapConfig->getOptionalString('search.filter', null);
214
215
        $filter = '';
216
        foreach ($searchAttributes as $attr) {
217
            $filter .= '(' . $attr . '=' . $username . ')';
218
        }
219
        $filter = '(|' . $filter . ')';
220
221
        // Append LDAP filters if defined
222
        if ($searchFilter !== null) {
223
            $filter = "(&" . $filter . $searchFilter . ")";
224
        }
225
226
        return $filter;
227
    }
228
}
229