Passed
Push — devel-3.0 ( 5a06ca...84adb8 )
by Rubén
03:54
created

LdapMsAds::checkUserInGroupByFilter()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 22
nc 2
nop 1
dl 0
loc 32
rs 9.568
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Providers\Auth\Ldap;
26
27
use SP\Core\Events\Event;
28
use SP\Core\Events\EventMessage;
29
use SP\Http\Address;
30
31
/**
32
 * Class LdapAds
33
 *
34
 * Autentificación basada en Active Directory
35
 *
36
 * @package SP\Auth\Ldap
37
 */
38
final class LdapMsAds extends Ldap
39
{
40
    const FILTER_USER_OBJECT = '(|(objectCategory=person)(objectClass=user))';
41
    const FILTER_GROUP_OBJECT = '(objectCategory=group)';
42
    const FILTER_USER_ATTRIBUTES = ['samaccountname', 'cn', 'uid', 'userPrincipalName'];
43
    const FILTER_GROUP_ATTRIBUTES = ['memberOf', 'groupMembership', 'memberof:1.2.840.113556.1.4.1941:='];
44
45
46
    /**
47
     * Devolver el filtro para comprobar la pertenecia al grupo
48
     *
49
     * @return string
50
     * @throws \SP\Core\Exceptions\SPException
51
     */
52
    public function getGroupMembershipFilter(): string
53
    {
54
        if (empty($this->ldapParams->getGroup())) {
55
            return self::FILTER_USER_OBJECT;
56
        }
57
58
        return '(&(|'
59
            . LdapUtil::getAttributesForFilter(
60
                self::FILTER_GROUP_ATTRIBUTES,
61
                $this->getGroupDn())
62
            . ')'
63
            . self::FILTER_USER_OBJECT
64
            . ')';
65
    }
66
67
    /**
68
     * Obtener el filtro para buscar el usuario
69
     *
70
     * @param string $userLogin
71
     *
72
     * @return string
73
     */
74
    public function getUserDnFilter(string $userLogin): string
75
    {
76
        return '(&(|'
77
            . LdapUtil::getAttributesForFilter(self::FILTER_USER_ATTRIBUTES, $userLogin)
78
            . ')'
79
            . self::FILTER_USER_OBJECT
80
            . ')';
81
    }
82
83
    /**
84
     * Devolver el filtro para objetos del tipo grupo
85
     *
86
     * @return string
87
     */
88
    public function getGroupObjectFilter(): string
89
    {
90
        return self::FILTER_GROUP_OBJECT;
91
    }
92
93
    /**
94
     * Buscar al usuario en un grupo.
95
     *
96
     * @param string $userDn
97
     * @param array  $groupsDn
98
     *
99
     * @return bool
100
     * @throws LdapException
101
     */
102
    public function isUserInGroup(string $userDn, array $groupsDn): bool
103
    {
104
        // Comprobar si está establecido el filtro de grupo o el grupo coincide con
105
        // los grupos del usuario
106
        if (empty($this->ldapParams->getGroup())
107
            || $this->ldapParams->getGroup() === '*'
108
            || in_array($this->getGroupDn(), $groupsDn)
109
        ) {
110
            $this->eventDispatcher->notifyEvent('ldap.check.group',
111
                new Event($this, EventMessage::factory()
112
                    ->addDescription(__u('Usuario verificado en grupo'))
113
                    ->addDetail(__u('Usuario'), $userDn)));
114
115
            return true;
116
        }
117
118
        return $this->checkUserInGroupByFilter($userDn);
119
    }
120
121
    /**
122
     * @param string $userDn
123
     *
124
     * @return bool
125
     * @throws LdapException
126
     */
127
    private function checkUserInGroupByFilter(string $userDn): bool
128
    {
129
        $groupDn = $this->getGroupDn();
130
131
        $filter = '(&(|'
132
            . LdapUtil::getAttributesForFilter(self::FILTER_USER_ATTRIBUTES, $userDn)
133
            . ')(|'
134
            . LdapUtil::getAttributesForFilter(self::FILTER_GROUP_ATTRIBUTES, $groupDn)
135
            . '))';
136
137
        $searchResults = $this->ldapActions->getObjects($filter, ['dn']);
138
139
        if (isset($searchResults['count'])
140
            && (int)$searchResults['count'] === 0
141
        ) {
142
            $this->eventDispatcher->notifyEvent('ldap.check.group',
143
                new Event($this, EventMessage::factory()
144
                    ->addDescription(__u('Usuario no pertenece al grupo'))
145
                    ->addDetail(__u('Usuario'), $userDn)
146
                    ->addDetail(__u('Grupo'), $groupDn)
147
                    ->addDetail('LDAP FILTER', $filter)));
148
149
            return false;
150
        }
151
152
        $this->eventDispatcher->notifyEvent('ldap.check.group',
153
            new Event($this, EventMessage::factory()
154
                ->addDescription(__u('Usuario verificado en grupo'))
155
                ->addDetail(__u('Usuario'), $userDn)
156
                ->addDetail(__u('Grupo'), $groupDn)));
157
158
        return true;
159
    }
160
161
    /**
162
     * Obtener el servidor de LDAP a utilizar
163
     *
164
     * @return mixed
165
     */
166
    protected function pickServer()
167
    {
168
        $server = $this->ldapParams->getServer();
169
170
        if (preg_match(Address::PATTERN_IP_ADDRESS, $server)) {
171
            return $server;
172
        }
173
174
        $serverDomain = '';
175
        $serverFQDN = explode('.', $server);
176
177
        for ($i = 1; $i <= count($serverFQDN) - 1; $i++) {
178
            $serverDomain .= $serverFQDN[$i] . '.';
179
        }
180
181
        $dnsServerQuery = '_msdcs.' . $serverDomain;
182
        $records = dns_get_record($dnsServerQuery, DNS_NS);
183
184
        if (count($records) === 0) {
185
            return $server;
186
        }
187
188
        $ads = [];
189
190
        foreach ($records as $record) {
191
            $ads[] = $record['target'];
192
        };
193
194
        $nAds = count($ads);
195
196
        return $nAds > 0 ? $ads[mt_rand(0, $nAds)] : $server;
197
    }
198
199
    /**
200
     * @return bool
201
     * @throws \SP\Core\Exceptions\SPException
202
     */
203
    protected function connect()
204
    {
205
        $handler = parent::connect();
206
207
        @ldap_set_option($handler, LDAP_OPT_REFERRALS, 0);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for ldap_set_option(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

207
        /** @scrutinizer ignore-unhandled */ @ldap_set_option($handler, LDAP_OPT_REFERRALS, 0);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
208
209
        return true;
210
    }
211
}