This file is indexed.

/usr/share/php/Horde/Auth/Ldap.php is in php-horde-auth 2.2.2-1ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
<?php
/**
 * Copyright 1999-2017 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL). If you did
 * not receive this file, see http://www.horde.org/licenses/lgpl21.
 *
 * @author   Jon Parise <jon@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl21 LGPL-2.1
 * @package  Auth
 */

/**
 * The Horde_Auth_Ldap class provides an LDAP implementation of the Horde
 * authentication system.
 *
 * 'preauthenticate' hook should return LDAP connection information in the
 * 'ldap' credentials key.
 *
 * @author    Jon Parise <jon@horde.org>
 * @category  Horde
 * @copyright 1999-2017 Horde LLC
 * @license   http://www.horde.org/licenses/lgpl21 LGPL-2.1
 * @package   Auth
 */
class Horde_Auth_Ldap extends Horde_Auth_Base
{
    /**
     * An array of capabilities, so that the driver can report which
     * operations it supports and which it doesn't.
     *
     * @var array
     */
    protected $_capabilities = array(
        'add' => true,
        'update' => true,
        'resetpassword' => true,
        'remove' => true,
        'list' => true,
        'authenticate' => true,
    );

    /**
     * LDAP object
     *
     * @var Horde_Ldap
     */
    protected $_ldap;

    /**
     * Constructor.
     *
     * @param array $params  Required parameters:
     * <pre>
     * 'basedn' - (string) [REQUIRED] The base DN for the LDAP server.
     * 'filter' - (string) The LDAP formatted search filter to search for
     *            users. This setting overrides the 'objectclass' parameter.
     * 'ldap' - (Horde_Ldap) [REQUIRED] Horde LDAP object.
     * 'objectclass - (string|array): The objectclass filter used to search
     *                for users. Either a single or an array of objectclasses.
     * 'uid' - (string) [REQUIRED] The username search key.
     * </pre>
     *
     * @throws Horde_Auth_Exception
     * @throws InvalidArgumentException
     */
    public function __construct(array $params = array())
    {
        foreach (array('basedn', 'ldap', 'uid') as $val) {
            if (!isset($params[$val])) {
                throw new InvalidArgumentException(__CLASS__ . ': Missing ' . $val . ' parameter.');
            }
        }

        if (!empty($params['ad'])) {
            $this->_capabilities['resetpassword'] = false;
        }

        $this->_ldap = $params['ldap'];
        unset($params['ldap']);

        parent::__construct($params);
    }

    /**
     * Checks for shadowLastChange and shadowMin/Max support and returns their
     * values.  We will also check for pwdLastSet if Active Directory is
     * support is requested.  For this check to succeed we need to be bound
     * to the directory.
     *
     * @param string $dn  The dn of the user.
     *
     * @return array  Array with keys being "shadowlastchange", "shadowmin"
     *                "shadowmax", "shadowwarning" and containing their
     *                respective values or false for no support.
     */
    protected function _lookupShadow($dn)
    {
        /* Init the return array. */
        $lookupshadow = array(
            'shadowlastchange' => false,
            'shadowmin' => false,
            'shadowmax' => false,
            'shadowwarning' => false
        );

        /* According to LDAP standard, to read operational attributes, you
         * must request them explicitly. Attributes involved in password
         * expiration policy:
         *    pwdlastset: Active Directory
         *    shadow*: shadowUser schema
         *    passwordexpirationtime: Sun and Fedora Directory Server */
        try {
            $result = $this->_ldap->search(null, '(objectClass=*)', array(
                'attributes' => array(
                    'pwdlastset',
                    'shadowmax',
                    'shadowmin',
                    'shadowlastchange',
                    'shadowwarning',
                    'passwordexpirationtime'
                ),
                'scope' => 'base'
            ));
        } catch (Horde_Ldap_Exception $e) {
            return $lookupshadow;
        }

        if (!$result) {
            return $lookupshadow;
        }

        $info = reset($result);

        // TODO: 'ad'?
        if (!empty($this->_params['ad'])) {
            if (isset($info['pwdlastset'][0])) {
                /* Active Directory handles timestamps a bit differently.
                 * Convert the timestamp to a UNIX timestamp. */
                $lookupshadow['shadowlastchange'] = floor((($info['pwdlastset'][0] / 10000000) - 11644406783) / 86400) - 1;

                /* Password expiry attributes are in a policy. We cannot
                 * read them so use the Horde config. */
                $lookupshadow['shadowwarning'] = $this->_params['warnage'];
                $lookupshadow['shadowmin'] = $this->_params['minage'];
                $lookupshadow['shadowmax'] = $this->_params['maxage'];
            }
        } elseif (isset($info['passwordexpirationtime'][0])) {
            /* Sun/Fedora Directory Server uses a special attribute
             * passwordexpirationtime.  It has precedence over shadow*
             * because it actually locks the expired password at the LDAP
             * server level.  The correct way to check expiration should
             * be using LDAP controls, unfortunately PHP doesn't support
             * controls on bind() responses. */
            $ldaptimepattern = "/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})Z/";
            if (preg_match($ldaptimepattern, $info['passwordexpirationtime'][0], $regs)) {
                /* Sun/Fedora Directory Server return expiration time, not
                 * last change time. We emulate the behaviour taking it
                 * back to maxage. */
                $lookupshadow['shadowlastchange'] = floor(mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]) / 86400) - $this->_params['maxage'];

                /* Password expiry attributes are in not accessible policy
                 * entry. */
                $lookupshadow['shadowwarning'] = $this->_params['warnage'];
                $lookupshadow['shadowmin']     = $this->_params['minage'];
                $lookupshadow['shadowmax']     = $this->_params['maxage'];
            } elseif ($this->_logger) {
                $this->_logger->log('Wrong time format: ' . $info['passwordexpirationtime'][0], 'ERR');
            }
        } else {
            if (isset($info['shadowmax'][0])) {
                $lookupshadow['shadowmax'] = $info['shadowmax'][0];
            }
            if (isset($info['shadowmin'][0])) {
                $lookupshadow['shadowmin'] = $info['shadowmin'][0];
            }
            if (isset($info['shadowlastchange'][0])) {
                $lookupshadow['shadowlastchange'] = $info['shadowlastchange'][0];
            }
            if (isset($info['shadowwarning'][0])) {
                $lookupshadow['shadowwarning'] = $info['shadowwarning'][0];
            }
        }

        return $lookupshadow;
    }

    /**
     * Find out if the given set of login credentials are valid.
     *
     * @param string $userId       The userId to check.
     * @param array  $credentials  An array of login credentials.
     *
     * @throws Horde_Auth_Exception
     */
    protected function _authenticate($userId, $credentials)
    {
        if (!strlen($credentials['password'])) {
            throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
        }

        /* Search for the user's full DN. */
        $this->_ldap->bind();
        try {
            $dn = $this->_ldap->findUserDN($userId);
        } catch (Horde_Exception_NotFound $e) {
            throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
        } catch (Horde_Exception_Ldap $e) {
            throw new Horde_Auth_Exception($e->getMessage(), Horde_Auth::REASON_MESSAGE);
        }

        /* Attempt to bind to the LDAP server as the user. */
        try {
            $this->_ldap->bind($dn, $credentials['password']);
            // Be sure we rebind as the configured user.
            $this->_ldap->bind();
        } catch (Horde_Ldap_Exception $e) {
            // Be sure we rebind as the configured user.
            $this->_ldap->bind();
            if (Horde_Ldap::errorName($e->getCode() == 'LDAP_INVALID_CREDENTIALS')) {
                throw new Horde_Auth_Exception('', Horde_Auth::REASON_BADLOGIN);
            }
            throw new Horde_Auth_Exception($e->getMessage(), Horde_Auth::REASON_MESSAGE);
        }

        if ($this->_params['password_expiration'] == 'yes') {
            $shadow = $this->_lookupShadow($dn);
            if ($shadow['shadowmax'] && $shadow['shadowlastchange'] &&
                $shadow['shadowwarning']) {
                $today = floor(time() / 86400);
                $toexpire = $shadow['shadowlastchange'] +
                            $shadow['shadowmax'] - $today;

                $warnday = $shadow['shadowlastchange'] + $shadow['shadowmax'] - $shadow['shadowwarning'];
                if ($today >= $warnday) {
                    $this->setCredential('expire', $toexpire);
                }

                if ($toexpire == 0) {
                    $this->setCredential('change', true);
                } elseif ($toexpire < 0) {
                    throw new Horde_Auth_Exception('', Horde_Auth::REASON_EXPIRED);
                }
            }
        }
    }

    /**
     * Add a set of authentication credentials.
     *
     * @param string $userId      The userId to add.
     * @param array $credentials  The credentials to be set.
     *
     * @throws Horde_Auth_Exception
     */
    public function addUser($userId, $credentials)
    {
        if (!empty($this->_params['ad'])) {
            throw new Horde_Auth_Exception(__CLASS__ . ': Adding users is not supported for Active Directory.');
        }

        if (isset($credentials['ldap'])) {
            $entry = $credentials['ldap'];
            $dn = $entry['dn'];

            /* Remove the dn entry from the array. */
            unset($entry['dn']);
        } else {
            /* Try this simple default and hope it works. */
            $dn = $this->_params['uid'] . '=' . $userId . ','
                . $this->_params['basedn'];
            $entry['cn'] = $userId;
            $entry['sn'] = $userId;
            $entry[$this->_params['uid']] = $userId;
            $entry['objectclass'] = array_merge(
                array('top'),
                $this->_params['newuser_objectclass']);
            $entry['userPassword'] = Horde_Auth::getCryptedPassword(
                $credentials['password'], '',
                $this->_params['encryption'],
                'true');

            if ($this->_params['password_expiration'] == 'yes') {
                $entry['shadowMin'] = $this->_params['minage'];
                $entry['shadowMax'] = $this->_params['maxage'];
                $entry['shadowWarning'] = $this->_params['warnage'];
                $entry['shadowLastChange'] = floor(time() / 86400);
            }
        }

        try {
            $this->_ldap->add(Horde_Ldap_Entry::createFresh($dn, $entry));
        } catch (Horde_Ldap_Exception $e) {
            throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to add user "%s". This is what the server said: ', $userId) . $e->getMessage());
        }
    }

    /**
     * Remove a set of authentication credentials.
     *
     * @param string $userId  The userId to add.
     * @param string $dn      TODO
     *
     * @throws Horde_Auth_Exception
     */
    public function removeUser($userId, $dn = null)
    {
        if (!empty($this->_params['ad'])) {
            throw new Horde_Auth_Exception(__CLASS__ . ': Removing users is not supported for Active Directory');
        }

        if (is_null($dn)) {
            /* Search for the user's full DN. */
            try {
                $dn = $this->_ldap->findUserDN($userId);
            } catch (Horde_Exception_Ldap $e) {
                throw new Horde_Auth_Exception($e);
            }
        }

        try {
            $this->_ldap->delete($dn);
        } catch (Horde_Ldap_Exception $e) {
            throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to remove user "%s"', $userId));
        }
    }

    /**
     * Update a set of authentication credentials.
     *
     * @todo Clean this up for Horde 5.
     *
     * @param string $oldID       The old userId.
     * @param string $newID       The new userId.
     * @param array $credentials  The new credentials.
     * @param string $olddn       The old user DN.
     * @param string $newdn       The new user DN.
     *
     * @throws Horde_Auth_Exception
     */
    public function updateUser($oldID, $newID, $credentials, $olddn = null,
                               $newdn = null)
    {
        if (!empty($this->_params['ad'])) {
            throw new Horde_Auth_Exception(__CLASS__ . ': Updating users is not supported for Active Directory.');
        }

        if (is_null($olddn)) {
            /* Search for the user's full DN. */
            try {
                $dn = $this->_ldap->findUserDN($oldID);
            } catch (Horde_Exception_Ldap $e) {
                throw new Horde_Auth_Exception($e);
            }

            $olddn = $dn;
            $newdn = preg_replace('/uid=.*?,/', 'uid=' . $newID . ',', $dn, 1);
            $shadow = $this->_lookupShadow($dn);

            /* If shadowmin hasn't yet expired only change when we are
               administrator */
            if ($shadow['shadowlastchange'] &&
                $shadow['shadowmin'] &&
                ($shadow['shadowlastchange'] + $shadow['shadowmin'] > (time() / 86400))) {
                throw new Horde_Auth_Exception('Minimum password age has not yet expired');
            }

            /* Set the lastchange field */
            if ($shadow['shadowlastchange']) {
                $entry['shadowlastchange'] =  floor(time() / 86400);
            }

            /* Encrypt the new password */
            $entry['userpassword'] = Horde_Auth::getCryptedPassword(
                $credentials['password'], '',
                $this->_params['encryption'],
                'true');
        } else {
            $entry = $credentials;
            unset($entry['dn']);
        }

        try {
            if ($oldID != $newID) {
                $this->_ldap->move($olddn, $newdn);
                $this->_ldap->modify($newdn, array('replace' => $entry));
            } else {
                $this->_ldap->modify($olddn, array('replace' => $entry));
            }
        } catch (Horde_Ldap_Exception $e) {
            throw new Horde_Auth_Exception(sprintf(__CLASS__ . ': Unable to update user "%s"', $newID));
        }
    }

    /**
     * Reset a user's password. Used for example when the user does not
     * remember the existing password.
     *
     * @param string $userId  The user id for which to reset the password.
     *
     * @return string  The new password on success.
     * @throws Horde_Auth_Exception
     */
    public function resetPassword($userId)
    {
        if (!empty($this->_params['ad'])) {
            throw new Horde_Auth_Exception(__CLASS__ . ': Updating users is not supported for Active Directory.');
        }

        /* Search for the user's full DN. */
        try {
            $dn = $this->_ldap->findUserDN($userId);
        } catch (Horde_Exception_Ldap $e) {
            throw new Horde_Auth_Exception($e);
        }

        /* Get a new random password. */
        $password = Horde_Auth::genRandomPassword();

        /* Encrypt the new password */
        $entry = array(
            'userpassword' => Horde_Auth::getCryptedPassword($password,
                                                             '',
                                                             $this->_params['encryption'],
                                                             'true'));

        /* Set the lastchange field */
        $shadow = $this->_lookupShadow($dn);
        if ($shadow['shadowlastchange']) {
            $entry['shadowlastchange'] = floor(time() / 86400);
        }

        /* Update user entry. */
        try {
            $this->_ldap->modify($dn, array('replace' => $entry));
        } catch (Horde_Ldap_Exception $e) {
            throw new Horde_Auth_Exception($e);
        }

        return $password;
    }

    /**
     * Lists all users in the system.
     *
     * @param boolean $sort  Sort the users?
     *
     * @return array  The array of userIds.
     * @throws Horde_Auth_Exception
     */
    public function listUsers($sort = false)
    {
        $params = array(
            'attributes' => array($this->_params['uid']),
            'scope' => $this->_params['scope'],
            'sizelimit' => isset($this->_params['sizelimit']) ? $this->_params['sizelimit'] : 0
        );

        /* Add a sizelimit, if specified. Default is 0, which means no limit.
         * Note: You cannot override a server-side limit with this. */
        $userlist = array();
        try {
            $search = $this->_ldap->search(
                $this->_params['basedn'],
                Horde_Ldap_Filter::build(array('filter' => $this->_params['filter'])),
                $params);
            $uid = Horde_String::lower($this->_params['uid']);
            foreach ($search as $val) {
                $userlist[] = $val->getValue($uid, 'single');
            }
        } catch (Horde_Ldap_Exception $e) {
        }

        return $this->_sort($userlist, $sort);
    }

    /**
     * Checks if $userId exists in the LDAP backend system.
     *
     * @author Marco Ferrante, University of Genova (I)
     *
     * @param string $userId  User ID for which to check
     *
     * @return boolean  Whether or not $userId already exists.
     */
    public function exists($userId)
    {
        $params = array(
            'scope' => $this->_params['scope']
        );

        try {
            $uidfilter = Horde_Ldap_Filter::create($this->_params['uid'], 'equals', $userId);
            $classfilter = Horde_Ldap_Filter::build(array('filter' => $this->_params['filter']));

            $search = $this->_ldap->search(
                $this->_params['basedn'],
                Horde_Ldap_Filter::combine('and', array($uidfilter, $classfilter)),
                $params);
            if ($search->count() < 1) {
                return false;
            }
            if ($search->count() > 1 && $this->_logger) {
                $this->_logger->log('Multiple LDAP entries with user identifier ' . $userId, 'WARN');
            }
            return true;
        } catch (Horde_Ldap_Exception $e) {
            if ($this->_logger) {
                $this->_logger->log('Error searching LDAP user: ' . $e->getMessage(), 'ERR');
            }
            return false;
        }
    }
}