Passed
Pull Request — master (#37)
by Tim
28:28 queued 20:25
created

Ldap::resolveConnector()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 16
c 0
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\ConnectorFactory;
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 = ConnectorFactory::fromAuthSourceConfig($config);
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
        $searchScope = $this->ldapConfig->getOptionalString('search.scope', Query::SCOPE_SUB);
75
        Assert::oneOf($searchScope, [Query::SCOPE_BASE, Query::SCOPE_ONE, Query::SCOPE_SUB]);
76
77
        $timeout = $this->ldapConfig->getOptionalInteger('timeout', 3);
78
        Assert::natural($timeout);
79
80
        $searchBase = $this->ldapConfig->getArray('search.base');
81
        $options = [
82
            'scope' => $searchScope,
83
            'timeout' => $timeout,
84
        ];
85
86
        $searchEnable = $this->ldapConfig->getOptionalBoolean('search.enable', false);
87
        if ($searchEnable === false) {
88
            $dnPattern = $this->ldapConfig->getString('dnpattern');
89
            $dn = str_replace('%username%', $username, $dnPattern);
90
        } else {
91
            $searchUsername = $this->ldapConfig->getString('search.username');
92
            Assert::notWhitespaceOnly($searchUsername);
93
94
            $searchPassword = $this->ldapConfig->getOptionalString('search.password', null);
95
            Assert::nullOrnotWhitespaceOnly($searchPassword);
96
97
            $searchAttributes = $this->ldapConfig->getArray('search.attributes');
98
            $searchFilter = $this->ldapConfig->getOptionalString('search.filter', null);
99
100
            try {
101
                $this->connector->bind($searchUsername, $searchPassword);
102
            } catch (Error\Error $e) {
103
                throw new Error\Exception("Unable to bind using the configured search.username and search.password.");
104
            }
105
106
            $filter = '';
107
            foreach ($searchAttributes as $attr) {
108
                $filter .= '(' . $attr . '=' . $username . ')';
109
            }
110
            $filter = '(|' . $filter . ')';
111
112
            // Append LDAP filters if defined
113
            if ($searchFilter !== null) {
114
                $filter = "(&" . $filter . $searchFilter . ")";
115
            }
116
117
            try {
118
                /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
119
                $entry = $this->connector->search($searchBase, $filter, $options, false);
120
                $dn = $entry->getDn();
121
            } catch (Error\Exception $e) {
122
                throw new Error\Error('WRONGUSERPASS');
123
            }
124
        }
125
126
        $this->connector->bind($dn, $password);
127
128
        $options['scope'] = Query::SCOPE_BASE;
129
        $filter = '(objectClass=*)';
130
131
        /** @psalm-var \Symfony\Component\Ldap\Entry $entry */
132
        $entry = $this->connector->search([$dn], $filter, $options, false);
133
134
        $attributes = $this->ldapConfig->getOptionalValue('attributes', []);
135
        if ($attributes === null) {
136
            $result = $entry->getAttributes();
137
        } else {
138
            Assert::isArray($attributes);
139
            $result = array_intersect_key(
140
                $entry->getAttributes(),
141
                array_fill_keys(array_values($attributes), null)
142
            );
143
        }
144
145
        $binaries = array_intersect(
146
            array_keys($result),
147
            $this->ldapConfig->getOptionalArray('attributes.binary', []),
148
        );
149
        foreach ($binaries as $binary) {
150
            $result[$binary] = array_map('base64_encode', $result[$binary]);
151
        }
152
153
        return $result;
154
    }
155
}
156