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

LdapStd::getGroupObjectFilter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
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
30
/**
31
 * Class LdapStd
32
 *
33
 * Autentificación basada en LDAP estándard
34
 *
35
 * @package SP\Auth\Ldap
36
 */
37
final class LdapStd extends Ldap
38
{
39
    const FILTER_USER_OBJECT = '(|(objectClass=inetOrgPerson)(objectClass=person)(objectClass=simpleSecurityObject))';
40
    const FILTER_GROUP_OBJECT = '(|(objectClass=groupOfNames)(objectClass=groupOfUniqueNames)(objectClass=group))';
41
    const FILTER_USER_ATTRIBUTES = ['samaccountname', 'cn', 'uid', 'userPrincipalName'];
42
    const FILTER_GROUP_ATTRIBUTES = ['memberOf', 'groupMembership'];
43
44
    /**
45
     * Devolver el filtro para objetos del tipo grupo
46
     *
47
     * @return string
48
     */
49
    public function getGroupObjectFilter(): string
50
    {
51
        return self::FILTER_GROUP_OBJECT;
52
    }
53
54
    /**
55
     * Devolver el filtro para comprobar la pertenecia al grupo
56
     *
57
     * @return string
58
     * @throws \SP\Core\Exceptions\SPException
59
     */
60
    public function getGroupMembershipFilter(): string
61
    {
62
        if (empty($this->ldapParams->getGroup())) {
63
            return self::FILTER_USER_OBJECT;
64
        }
65
66
        return '(&(|'
67
            . LdapUtil::getAttributesForFilter(
68
                self::FILTER_GROUP_ATTRIBUTES,
69
                $this->getGroupDn())
70
            . ')' . self::FILTER_USER_OBJECT
71
            . ')';
72
    }
73
74
    /**
75
     * Obtener el filtro para buscar el usuario
76
     *
77
     * @param string $userLogin
78
     *
79
     * @return mixed
80
     */
81
    public function getUserDnFilter(string $userLogin): string
82
    {
83
        return '(&(|'
84
            . LdapUtil::getAttributesForFilter(self::FILTER_USER_ATTRIBUTES, $userLogin)
85
            . ')'
86
            . self::FILTER_USER_OBJECT
87
            . ')';
88
    }
89
90
    /**
91
     * Buscar al usuario en un grupo.
92
     *
93
     * @param string $userDn
94
     * @param array  $groupsDn
95
     *
96
     * @return bool
97
     * @throws LdapException
98
     */
99
    public function isUserInGroup(string $userDn, array $groupsDn): bool
100
    {
101
        // Comprobar si está establecido el filtro de grupo o el grupo coincide con
102
        // los grupos del usuario
103
        if (empty($this->ldapParams->getGroup())
104
            || $this->ldapParams->getGroup() === '*'
105
            || in_array($this->getGroupDn(), $groupsDn)
106
        ) {
107
            $this->eventDispatcher->notifyEvent('ldap.check.group',
108
                new Event($this, EventMessage::factory()
109
                    ->addDescription(__u('Usuario verificado en grupo'))
110
                    ->addDetail(__u('Usuario'), $userDn)));
111
112
            return true;
113
        }
114
115
        return $this->checkUserInGroupByFilter($userDn);
116
    }
117
118
    /**
119
     * @param string $userDn
120
     *
121
     * @return bool
122
     * @throws LdapException
123
     */
124
    private function checkUserInGroupByFilter(string $userDn): bool
125
    {
126
        $groupName = ldap_escape($this->getGroupFromParams(), null, LDAP_ESCAPE_FILTER);
127
        $userDN = ldap_escape($userDn, null, LDAP_ESCAPE_FILTER);
128
        $filter = '(&(cn=' . $groupName . ')'
129
            . '(|(memberUid=' . $userDN . ')(member=' . $userDN . ')(uniqueMember=' . $userDN . '))'
130
            . self::FILTER_GROUP_OBJECT
131
            . ')';
132
133
        $searchResults = $this->ldapActions->getObjects($filter, ['dn']);
134
135
        if (isset($searchResults['count'])
136
            && (int)$searchResults['count'] === 0
137
        ) {
138
            $this->eventDispatcher->notifyEvent('ldap.check.group',
139
                new Event($this, EventMessage::factory()
140
                    ->addDescription(__u('Usuario no pertenece al grupo'))
141
                    ->addDetail(__u('Usuario'), $userDn)
142
                    ->addDetail(__u('Grupo'), $groupName)
143
                    ->addDetail('LDAP FILTER', $filter)));
144
145
            return false;
146
        }
147
148
        return true;
149
    }
150
151
    /**
152
     * Obtener el servidor de LDAP a utilizar
153
     *
154
     * @return mixed
155
     */
156
    protected function pickServer()
157
    {
158
        return $this->ldapParams->getServer();
159
    }
160
161
    /**
162
     * @return bool
163
     * @throws \SP\Core\Exceptions\SPException
164
     */
165
    protected function connect()
166
    {
167
        $handler = parent::connect();
168
169
        @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

169
        /** @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...
170
171
        return true;
172
    }
173
}