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

Ldap::resolveConnector()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 16
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 23
rs 9.7333
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
131
        $options['scope'] = Query::SCOPE_BASE;
132
        $filter = '(objectClass=*)';
133
134
        /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
135
        $entry = $this->connector->search([$dn], $filter, $options, false);
136
137
        $attributes = $this->ldapConfig->getOptionalValue('attributes', []);
138
        if ($attributes === null) {
139
            $result = $entry->getAttributes();
140
        } else {
141
            Assert::isArray($attributes);
142
            $result = array_intersect_key(
143
                $entry->getAttributes(),
144
                array_fill_keys(array_values($attributes), null)
145
            );
146
        }
147
148
        $binaries = array_intersect(
149
            array_keys($result),
150
            $this->ldapConfig->getOptionalArray('attributes.binary', []),
151
        );
152
        foreach ($binaries as $binary) {
153
            $result[$binary] = array_map('base64_encode', $result[$binary]);
154
        }
155
156
        return $result;
157
    }
158
159
    /**
160
     * Resolve the connector
161
     *
162
     * @return \SimpleSAML\Module\ldap\ConnectorInterface
163
     * @throws \Exception
164
     */
165
    protected function resolveConnector(): ConnectorInterface
166
    {
167
        if (!empty($this->connector)) {
168
            return $this->connector;
169
        }
170
171
        $encryption = $this->ldapConfig->getOptionalString('encryption', 'ssl');
172
        Assert::oneOf($encryption, ['none', 'ssl', 'tls']);
173
174
        $version = $this->ldapConfig->getOptionalInteger('version', 3);
175
        Assert::positiveInteger($version);
176
177
        $class = $this->ldapConfig->getOptionalString('connector', Connector\Ldap::class);
178
        Assert::classExists($class);
179
        Assert::implementsInterface($class, ConnectorInterface::class);
180
181
        return $this->connector = new $class(
182
            $this->ldapConfig->getString('connection_string'),
183
            $encryption,
184
            $version,
185
            $this->ldapConfig->getOptionalString('extension', 'ext_ldap'),
186
            $this->ldapConfig->getOptionalBoolean('debug', false),
187
            $this->ldapConfig->getOptionalArray('options', []),
188
        );
189
    }
190
}
191