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

Ldap::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
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\Connector;
12
use SimpleSAML\Module\ldap\ConnectorInterface;
13
use Symfony\Component\Ldap\Adapter\ExtLdap\Query;
14
15
use function array_fill_keys;
16
use function array_keys;
17
use function array_map;
18
use function array_values;
19
use function sprintf;
20
use function str_replace;
21
use function var_export;
22
23
/**
24
 * LDAP authentication source.
25
 *
26
 * See the ldap-entry in config-templates/authsources.php for information about
27
 * configuration of this authentication source.
28
 *
29
 * @package simplesamlphp/simplesamlphp-module-ldap
30
 */
31
32
class Ldap extends UserPassBase
33
{
34
    /**
35
     * @var \SimpleSAML\Module\ldap\ConnectorInterface
36
     */
37
    protected ConnectorInterface $connector;
38
39
    /**
40
     * An LDAP configuration object.
41
     */
42
    protected Configuration $ldapConfig;
43
44
45
    /**
46
     * Constructor for this authentication source.
47
     *
48
     * @param array $info  Information about this authentication source.
49
     * @param array $config  Configuration.
50
     */
51
    public function __construct(array $info, array $config)
52
    {
53
        // Call the parent constructor first, as required by the interface
54
        parent::__construct($info, $config);
55
56
        $this->ldapConfig = Configuration::loadFromArray(
57
            $config,
58
            'authsources[' . var_export($this->authId, true) . ']'
59
        );
60
61
        $this->connector = $this->resolveConnector();
62
    }
63
64
65
    /**
66
     * Attempt to log in using the given username and password.
67
     *
68
     * @param string $username  The username the user wrote.
69
     * @param string $password  The password the user wrote.
70
     * @return array  Associative array with the users attributes.
71
     */
72
    protected function login(string $username, string $password): array
73
    {
74
        $timeout = $this->ldapConfig->getOptionalInteger('timeout', 3);
75
        Assert::positiveInteger($timeout);
76
77
        $searchScope = $this->ldapConfig->getOptionalString('search.scope', Query::SCOPE_SUB);
78
        Assert::oneOf($searchScope, [Query::SCOPE_BASE, Query::SCOPE_ONE, Query::SCOPE_SUB]);
79
80
        $timeout = $this->ldapConfig->getOptionalInteger('timeout', 3);
81
        $searchBase = $this->ldapConfig->getArray('search.base');
82
        $options = [
83
            'scope' => $searchScope,
84
            'timeout' => $timeout,
85
        ];
86
87
        $connector = $this->resolveConnector();
0 ignored issues
show
Unused Code introduced by
The assignment to $connector is dead and can be removed.
Loading history...
88
89
        $searchEnable = $this->ldapConfig->getOptionalBoolean('search.enable', false);
90
        if ($searchEnable === false) {
91
            $dnPattern = $this->ldapConfig->getString('dnpattern');
92
            $dn = str_replace('%username%', $username, $dnPattern);
93
        } else {
94
            $searchUsername = $this->ldapConfig->getString('search.username');
95
            Assert::notWhitespaceOnly($searchUsername);
96
97
            $searchPassword = $this->ldapConfig->getOptionalString('search.password', null);
98
            Assert::nullOrnotWhitespaceOnly($searchPassword);
99
100
            $searchAttributes = $this->ldapConfig->getArray('search.attributes');
101
            $searchFilter = $this->ldapConfig->getOptionalString('search.filter', null);
102
103
            try {
104
                $this->connector->bind($searchUsername, $searchPassword);
105
            } catch (Error\Error $e) {
106
                throw new Error\Exception("Unable to bind using the configured search.username and search.password.");
107
            }
108
109
            $filter = '';
110
            foreach ($searchAttributes as $attr) {
111
                $filter .= '(' . $attr . '=' . $username . ')';
112
            }
113
            $filter = '(|' . $filter . ')';
114
115
            // Append LDAP filters if defined
116
            if ($searchFilter !== null) {
117
                $filter = "(&" . $filter . $searchFilter . ")";
118
            }
119
120
            try {
121
                /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
122
                $entry = $this->connector->search($searchBase, $filter, $options, false);
123
                $dn = $entry->getDn();
124
            } catch (Error\Exception $e) {
125
                throw new Error\Error('WRONGUSERPASS');
126
            }
127
        }
128
129
        $this->connector->bind($dn, $password);
130
        $filter = sprintf('(distinguishedName=%s)', $dn);
131
132
        /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
133
        $entry = $this->connector->search($searchBase, $filter, $options, false);
134
135
        $attributes = $this->ldapConfig->getOptionalValue('attributes', []);
136
        if ($attributes === null) {
137
            $result = $entry->getAttributes();
138
        } else {
139
            Assert::isArray($attributes);
140
            $result = array_intersect_key(
141
                $entry->getAttributes(),
142
                array_fill_keys(array_values($attributes), null)
143
            );
144
        }
145
146
        $binaries = array_intersect(
147
            array_keys($result),
148
            $this->ldapConfig->getOptionalArray('attributes.binary', []),
149
        );
150
        foreach ($binaries as $binary) {
151
            $result[$binary] = array_map('base64_encode', $result[$binary]);
152
        }
153
154
        return $result;
155
    }
156
157
    /**
158
     * Resolve the connector
159
     *
160
     * @return \SimpleSAML\Module\ldap\ConnectorInterface
161
     * @throws \Exception
162
     */
163
    protected function resolveConnector(): ConnectorInterface
164
    {
165
        if (!empty($this->connector)) {
166
            return $this->connector;
167
        }
168
169
        $encryption = $this->ldapConfig->getString('encryption', 'ssl');
0 ignored issues
show
Unused Code introduced by
The call to SimpleSAML\Configuration::getString() has too many arguments starting with 'ssl'. ( Ignorable by Annotation )

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

169
        /** @scrutinizer ignore-call */ 
170
        $encryption = $this->ldapConfig->getString('encryption', 'ssl');

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...
170
        Assert::oneOf($encryption, ['none', 'ssl', 'tls']);
171
172
        $version = $this->ldapConfig->getInteger('version', 3);
0 ignored issues
show
Unused Code introduced by
The call to SimpleSAML\Configuration::getInteger() has too many arguments starting with 3. ( Ignorable by Annotation )

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

172
        /** @scrutinizer ignore-call */ 
173
        $version = $this->ldapConfig->getInteger('version', 3);

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...
173
        Assert::positiveInteger($version);
174
175
        $class = $this->ldapConfig->getString('connector', Connector\Ldap::class);
176
        Assert::classExists($class);
177
        Assert::implementsInterface($class, ConnectorInterface::class);
178
179
        return $this->connector = new $class(
180
            $this->ldapConfig->getString('connection_string'),
181
            $encryption,
182
            $version,
183
            $this->ldapConfig->getString('extension', 'ext_ldap'),
184
            $this->ldapConfig->getBoolean('debug', false),
0 ignored issues
show
Unused Code introduced by
The call to SimpleSAML\Configuration::getBoolean() has too many arguments starting with false. ( Ignorable by Annotation )

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

184
            $this->ldapConfig->/** @scrutinizer ignore-call */ 
185
                               getBoolean('debug', false),

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...
185
            $this->ldapConfig->getArray('options', []),
0 ignored issues
show
Unused Code introduced by
The call to SimpleSAML\Configuration::getArray() has too many arguments starting with array(). ( Ignorable by Annotation )

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

185
            $this->ldapConfig->/** @scrutinizer ignore-call */ 
186
                               getArray('options', []),

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...
186
        );
187
    }
188
}
189