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

Ldap::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 11
rs 10
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
            $searchAttributes = $this->ldapConfig->getArray('search.attributes');
0 ignored issues
show
Unused Code introduced by
The assignment to $searchAttributes is dead and can be removed.
Loading history...
99
            $searchFilter = $this->ldapConfig->getOptionalString('search.filter', null);
0 ignored issues
show
Unused Code introduced by
The assignment to $searchFilter is dead and can be removed.
Loading history...
100
101
            try {
102
                $this->connector->bind($searchUsername, $searchPassword);
103
            } catch (Error\Error $e) {
104
                throw new Error\Exception("Unable to bind using the configured search.username and search.password.");
105
            }
106
107
            $filter = $this->buildSearchFilter($username);
108
109
            try {
110
                /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
111
                $entry = $this->connector->search($searchBase, $filter, $options, false);
112
                $dn = $entry->getDn();
113
            } catch (Error\Exception $e) {
114
                throw new Error\Error('WRONGUSERPASS');
115
            }
116
        }
117
118
        $this->connector->bind($dn, $password);
119
120
        $options['scope'] = Query::SCOPE_BASE;
121
        $filter = '(objectClass=*)';
122
123
        /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
124
        $entry = $this->connector->search([$dn], $filter, $options, false);
125
126
        return $this->processAttributes($entry);
0 ignored issues
show
Bug introduced by
It seems like $entry can also be of type null; however, parameter $entry of SimpleSAML\Module\ldap\A...ap::processAttributes() does only seem to accept Symfony\Component\Ldap\Entry, maybe add an additional type check? ( Ignorable by Annotation )

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

126
        return $this->processAttributes(/** @scrutinizer ignore-type */ $entry);
Loading history...
127
    }
128
129
130
    /**
131
     * Attempt to find a user's attributes given its username.
132
     *
133
     * @param string $username  The username who's attributes we want.
134
     * @return array  Associative array with the users attributes.
135
     */
136
    public function getAttributes(string $username): array
137
    {
138
        $searchUsername = $this->ldapConfig->getString('search.username');
139
        Assert::notWhitespaceOnly($searchUsername);
140
141
        $searchPassword = $this->ldapConfig->getOptionalString('search.password', null);
142
        Assert::nullOrnotWhitespaceOnly($searchPassword);
143
144
        try {
145
            $this->connector->bind($searchUsername, $searchPassword);
146
        } catch (Error\Error $e) {
147
            throw new Error\Exception("Unable to bind using the configured search.username and search.password.");
148
        }
149
150
        $searchEnable = $this->ldapConfig->getOptionalBoolean('search.enable', false);
151
        if ($searchEnable === false) {
152
            $dnPattern = $this->ldapConfig->getString('dnpattern');
153
            $filter = '(' . str_replace('%username%', $username, $dnPattern) . ')';
154
        } else {
155
            $filter = $this->buildSearchFilter($username);
156
        }
157
158
        $searchScope = $this->ldapConfig->getOptionalString('search.scope', Query::SCOPE_SUB);
159
        Assert::oneOf($searchScope, [Query::SCOPE_BASE, Query::SCOPE_ONE, Query::SCOPE_SUB]);
160
161
        $timeout = $this->ldapConfig->getOptionalInteger('timeout', 3);
162
        Assert::natural($timeout);
163
164
        $searchBase = $this->ldapConfig->getArray('search.base');
165
        $options = [
166
            'scope' => $searchScope,
167
            'timeout' => $timeout,
168
        ];
169
170
        try {
171
            /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
172
            $entry = $this->connector->search($searchBase, $filter, $options, false);
173
        } catch (Error\Exception $e) {
174
            throw new Error\Error('WRONGUSERPASS');
175
        }
176
177
        return $this->processAttributes($entry);
0 ignored issues
show
Bug introduced by
It seems like $entry can also be of type null; however, parameter $entry of SimpleSAML\Module\ldap\A...ap::processAttributes() does only seem to accept Symfony\Component\Ldap\Entry, maybe add an additional type check? ( Ignorable by Annotation )

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

177
        return $this->processAttributes(/** @scrutinizer ignore-type */ $entry);
Loading history...
178
    }
179
180
181
    /**
182
     * @param \Symfony\Component\Ldap\Entry $entry
183
     * @return array
184
     */
185
    private function processAttributes(Entry $entry): array
186
    {
187
        $attributes = $this->ldapConfig->getOptionalValue('attributes', []);
188
        if ($attributes === null) {
189
            $result = $entry->getAttributes();
190
        } else {
191
            Assert::isArray($attributes);
192
            $result = array_intersect_key(
193
                $entry->getAttributes(),
194
                array_fill_keys(array_values($attributes), null)
195
            );
196
        }
197
198
        $binaries = array_intersect(
199
            array_keys($result),
200
            $this->ldapConfig->getOptionalArray('attributes.binary', []),
201
        );
202
        foreach ($binaries as $binary) {
203
            $result[$binary] = array_map('base64_encode', $result[$binary]);
204
        }
205
206
        return $result;
207
    }
208
209
210
    /**
211
     * @param string $username
212
     * @return string
213
     */
214
    private function buildSearchFilter(string $username): string
215
    {
216
        $searchAttributes = $this->ldapConfig->getArray('search.attributes');
217
        /** @psalm-var string|null $searchFilter */
218
        $searchFilter = $this->ldapConfig->getOptionalString('search.filter', null);
219
220
        $filter = '';
221
        foreach ($searchAttributes as $attr) {
222
            $filter .= '(' . $attr . '=' . $username . ')';
223
        }
224
        $filter = '(|' . $filter . ')';
225
226
        // Append LDAP filters if defined
227
        if ($searchFilter !== null) {
228
            $filter = "(&" . $filter . $searchFilter . ")";
229
        }
230
231
        return $filter;
232
    }
233
}
234