forked from factorenergia/yii2-ldap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnection.php
765 lines (668 loc) · 20.8 KB
/
Connection.php
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
<?php
/**
* @link https://github.com/chrmorandi/yii2-ldap for the canonical source repository
* @package yii2-ldap
* @author Christopher Mota <[email protected]>
* @license MIT License - view the LICENSE file that was distributed with this source code.
*/
namespace websvc\ldap;
use Yii;
use yii\base\Component;
use yii\caching\Cache;
/**
* @property resource $resource
* @property boolean $bount
* @property int $errNo Error number of the last command
* @property string $lastError Error message of the last command
*
* @author Christopher Mota <[email protected]>
* @since 1.0
*/
class Connection extends Component
{
/**
* LDAP protocol string.
* @var string
*/
const PROTOCOL = 'ldap://';
/**
* LDAP port number.
* @var string
*/
const PORT = '389';
/**
* @event Event an event that is triggered after a DB connection is established
*/
const EVENT_AFTER_OPEN = 'afterOpen';
/**
* @var string the LDAP base dn.
*/
public $baseDn;
/**
* https://msdn.microsoft.com/en-us/library/ms677913(v=vs.85).aspx
* @var bool the integer to instruct the LDAP connection whether or not to follow referrals.
*/
public $followReferrals = false;
/**
* @var string The LDAP port to use when connecting to the domain controllers.
*/
public $port = self::PORT;
/**
* @var bool Determines whether or not to use TLS with the current LDAP connection.
*/
public $useTLS = true;
/**
* @var array the domain controllers to connect to.
*/
public $dc = [];
/**
* @var string the username for establishing LDAP connection. Defaults to `null` meaning no username to use.
*/
public $username;
/**
* @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
*/
public $password;
/**
* @var int The page size for the paging operation.
*/
public $pageSize = -1;
/**
* @var integer zero-based offset from where the records are to be returned. If not set or
* less than 1, it means not filter values.
*/
public $offset = -1;
/**
* @var boolean whether to enable caching.
* Note that in order to enable query caching, a valid cache component as specified
* by [[cache]] must be enabled and [[enableCache]] must be set true.
* Also, only the results of the queries enclosed within [[cache()]] will be cached.
* @see cacheDuration
* @see cache
*/
public $enableCache = true;
/**
* @var integer number of seconds that table metadata can remain valid in cache.
* Use 0 to indicate that the cached data will never expire.
* @see enableCache
*/
public $cacheDuration = 3600;
/**
* @var Cache|string the cache object or the ID of the cache application component that
* is used to cache result query.
* @see enableCache
*/
public $cache = 'cache';
/**
* @var string the attribute for authentication
*/
public $loginAttribute = "sAMAccountName";
/**
* @var bool stores the bool whether or not the current connection is bound.
*/
protected $_bound = false;
/**
* @var resource|false
*/
protected $resource;
/**
* @var string User Distinguished Names (DN)
*/
protected $userDN;
/**
* @var array with attributes of an entry, for when doing searches or retrieve data
* @author WebsvcPT
* @since 1.0.3
*/
public $dnAttributes = ['*'];
/**
* Cn string used to validate access.
*
* Ex:
* `cn=restricted,ou=Groups`
*
* Will be concatenated with $baseDn
* `cn=restricted,ou=Groups,dc=domain,dc=local`
*
* @var string
* @author WebsvcPT
* @since 1.0.5
*/
public $authAccess = [
'cn' => false, // Cn name, will be concatenated with baseDn
'objectClass' => false, // object class to search
'attributeMatch' => false, // attribute to match user
];
# Create AD password (Microsoft Active Directory password format)
protected static function encodePassword($password) {
$password = "\"" . $password . "\"";
$adpassword = mb_convert_encoding($password, "UTF-16LE", "UTF-8");
return $adpassword;
}
/**
* Returns the current query cache information.
* This method is used internally by [[Command]].
* @param integer $duration the preferred caching duration. If null, it will be ignored.
* @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
* @return array the current query cache information, or null if query cache is not enabled.
* @internal
*/
public function getCacheInfo($duration = 3600, $dependency = null)
{
if (!$this->enableCache) {
return null;
}
if ($duration === 0 || $duration > 0) {
if (is_string($this->cache) && Yii::$app) {
$cache = Yii::$app->get($this->cache, false);
} else {
$cache = $this->cache;
}
if ($cache instanceof Cache) {
return [$cache, $duration, $dependency];
}
}
return null;
}
/**
* Invalidates the cached data that are associated with any of the specified [[tags]] in this connection.
* @param string|array $tags
*/
public function clearCache($tags)
{
$cache = Yii::$app->get($this->cache, false);
\yii\caching\TagDependency::invalidate($cache, $tags);
}
/**
* Connects and Binds to the Domain Controller with a administrator credentials.
* @return void
*/
public function open($anonymous = false)
{
$token = 'Opening LDAP connection: ' . LdapUtils::recursive_implode($this->dc, ' or ');
Yii::info($token, __METHOD__);
Yii::beginProfile($token, __METHOD__);
// Connect to the LDAP server.
$this->connect($this->dc, $this->port);
Yii::endProfile($token, __METHOD__);
try {
if ($anonymous) {
$this->_bound = ldap_bind($this->resource);
} else {
$this->_bound = ldap_bind($this->resource, $this->username, $this->password);
}
} catch (\Exception $e) {
throw new \Exception('Invalid credential for user manager in ldap.', 0);
}
}
/**
* Connection.
* @param string|array $hostname
* @param type $port
* @return void
*/
protected function connect($hostname = [], $port = '389')
{
if (is_array($hostname)) {
$hostname = self::PROTOCOL.implode(' '.self::PROTOCOL, $hostname);
}
$this->close();
$this->resource = ldap_connect($hostname, $port);
// Set the LDAP options.
$this->setOption(LDAP_OPT_PROTOCOL_VERSION, 3);
$this->setOption(LDAP_OPT_REFERRALS, $this->followReferrals);
$this->setOption(LDAP_OPT_NETWORK_TIMEOUT, 2);
if ($this->useTLS) {
$this->startTLS();
}
$this->trigger(self::EVENT_AFTER_OPEN);
}
/**
* Authenticate user
* @param string $username
* @param string $password
* @return int indicate occurrence of error.
*/
public function auth($username, $password)
{
// Open connection with manager
$this->open();
# Search for user and get user DN
$searchResult = ldap_search(
$this->resource,
$this->baseDn,
"(&(objectClass=person)($this->loginAttribute=$username))",
[$this->loginAttribute]
);
$entry = $this->getFirstEntry($searchResult);
if($entry) {
$this->userDN = $this->getDn($entry);
} else {
$this->userDN = null;
}
// Connect to the LDAP server.
$this->connect($this->dc, $this->port);
// Authenticate user
return @ldap_bind($this->resource, $this->userDN, $password);
}
/**
* Reads a used record as array
* @return array
* @author WebsvcPT
* @since 1.0.3
*/
public function readUserData(){
$data = [];
try{
$entryRead = ldap_read(
$this->resource,
$this->userDN,
"(&(objectClass=person))",
$this->dnAttributes
);
// This is a bad way to do this
// Should used the count intead
$result = $this->getEntries($entryRead);
if($result['count']==1){
foreach ($result[0] as $key => $value) {
if( !is_numeric($key) ){
$data[$key]=$this->getElementValue($value);
}
}
}
} catch (Exception $e) {
// Not trowing errors here...
}
return $data;
}
/**
* Checks if $username is present in configured app cn, objectClass.
*
* @param type $username
*
* @return boolean
* @throws \Exception
*
* @author WebsvcPT
* @since 1.0.5
*/
public function checkUserAccess($username){
if(
$this->authAccess['cn'] != false
&& $this->authAccess['objectClass'] != false
&& $this->authAccess['attributeMatch'] != false
){
// Open connection with manager
$this->open();
$authorized = false;
try{
# Search for user in Cn
$searchResult = ldap_read(
$this->resource,
$this->authAccess['cn'] . ',' . $this->baseDn,
"(&(objectClass=".$this->authAccess['objectClass'].")(".$this->authAccess['attributeMatch']."=$username))",
['*']
);
$entry = $this->getFirstEntry($searchResult);
// $entry will be a resource OR False if not found
if($entry!==false){
$authorized = true;
}
} catch (Exception $e) {
// Not trowing errors here...
}
return $authorized;
}
throw new \Exception('Invalid Ldap extension settings.', 0);
}
/**
* Reads a user data and checks if user has access to a cn.
* Ex: Check if user has access to a group.
*
* @return array defined `dnAttributes` (uid) OR empty if user does not have access
* @author WebsvcPT
* @since 1.0.5
*/
public function checkAccessReturnUserdata(){
$userData = $this->readUserData();
if(empty($userData) || !$this->checkUserAccess($userData[$this->loginAttribute])) {
$userData = [];
}
return $userData;
}
/**
* Returns the string value of an element.
* Elements are generally a one key array, this will retrieve the first key only
*
* @param string|array $value
*
* @return string
*/
private function getElementValue($value){
if(is_array($value)){
return $value[0];
}
return $value;
}
/**
* Change the password of the current user. This must be performed over TLS.
* @param string $username User for change password
* @param string $oldPassword The old password
* @param string $newPassword The new password
* @return bool return true if change password is success
* @throws \Exception
*/
public function changePasswordAsUser($username, $oldPassword, $newPassword)
{
if (!$this->useTLS) {
$message = 'TLS must be configured on your web server and enabled to change passwords.';
throw new \Exception($message);
}
// Open connection with user
if(!$this->auth($username, $oldPassword)){
return false;
}
return $this->changePasswordAsManager($this->userDN, $newPassword);
}
/**
* Change the password of the user as manager. This must be performed over TLS.
* @param string $userDN User Distinguished Names (DN) for change password. Ex.: cn=admin,dc=example,dc=com
* @param string $newPassword The new password
* @return bool return true if change password is success
* @throws \Exception
*/
public function changePasswordAsManager($userDN, $newPassword)
{
if (!$this->useTLS) {
$message = 'TLS must be configured on your web server and enabled to change passwords.';
throw new \Exception($message);
}
// Open connection with manager
$this->open();
// Replace passowrd attribute for AD
// The AD password change procedure is modifying the attribute unicodePwd
$modifications['unicodePwd'] = self::encodePassword($newPassword);
return ldap_mod_replace($this->resource, $userDN, $modifications);
}
/**
* Closes the current connection.
*
* @return boolean
*/
public function close()
{
if (is_resource($this->resource)) {
ldap_close($this->resource);
}
return true;
}
/**
* Execute ldap search like.
*
* http://php.net/manual/en/ref.ldap.php
*
* @param string $function php LDAP function
* @param array $params params for execute ldap function
* @return bool|DataReader
*/
public function executeQuery($function, $params)
{
$this->open();
$results = [];
$cookie = '';
$token = $function . ' - params: ' . LdapUtils::recursive_implode($params, ';');
Yii::info($token , 'websvc\ldap\Connection::query');
Yii::beginProfile($token, 'websvc\ldap\Connection::query');
do {
if($this->pageSize > 0) {
$this->setControlPagedResult($cookie);
}
// Run the search.
$result = call_user_func($function, $this->resource, ...$params);
if($this->pageSize > 0) {
$this->setControlPagedResultResponse($result, $cookie);
}
//Collect each resource result
$results[] = $result;
} while (!is_null($cookie) && !empty($cookie));
Yii::endProfile($token, 'websvc\ldap\Connection::query');
return new DataReader($this, $results);
}
/**
* Returns true/false if the current connection is bound.
* @return bool
*/
public function getBound()
{
return $this->_bound;
}
/**
* Get the current resource of connection.
* @return resource
*/
public function getResource()
{
return $this->resource;
}
/**
* Sorts an AD search result by the specified attribute.
* @param resource $result
* @param string $attribute
* @return bool
*/
public function sort($result, $attribute)
{
return ldap_sort($this->resource, $result, $attribute);
}
/**
* Adds an entry to the current connection.
* @param string $dn
* @param array $entry
* @return bool
*/
public function add($dn, array $entry)
{
return ldap_add($this->resource, $dn, $entry);
}
/**
* Deletes an entry on the current connection.
* @param string $dn
* @return bool
*/
public function delete($dn)
{
return ldap_delete($this->resource, $dn);
}
/**
* Modify the name of an entry on the current connection.
*
* @param string $dn
* @param string $newRdn
* @param string $newParent
* @param bool $deleteOldRdn
* @return bool
*/
public function rename($dn, $newRdn, $newParent, $deleteOldRdn = false)
{
return ldap_rename($this->resource, $dn, $newRdn, $newParent, $deleteOldRdn);
}
/**
* Batch modifies an existing entry on the current connection.
* The types of modifications:
* LDAP_MODIFY_BATCH_ADD - Each value specified through values is added.
* LDAP_MODIFY_BATCH_REMOVE - Each value specified through values is removed.
* Any value of the attribute not contained in the values array will remain untouched.
* LDAP_MODIFY_BATCH_REMOVE_ALL - All values are removed from the attribute named by attrib.
* LDAP_MODIFY_BATCH_REPLACE - All current values are replaced by new one.
* @param string $dn
* @param array $values array associative with three keys: "attrib", "modtype" and "values".
* ```php
* [
* "attrib" => "attribute",
* "modtype" => LDAP_MODIFY_BATCH_ADD,
* "values" => ["attribute value one"],
* ],
* ```
* @return mixed
*/
public function modify($dn, array $values)
{
$this->clearCache(DataReader::CACHE_TAG);
return ldap_modify_batch($this->resource, $dn, $values);
}
/**
* Retrieve the entries from a search result.
* @param resource $searchResult
* @return array|boolean
*/
public function getEntries($searchResult)
{
return ldap_get_entries($this->resource, $searchResult);
}
/**
* Retrieves the number of entries from a search result.
* @param resource $searchResult
* @return int
*/
public function countEntries($searchResult)
{
return ldap_count_entries($this->resource, $searchResult);
}
/**
* Retrieves the first entry from a search result.
* @param resource $searchResult
* @return resource link identifier
*/
public function getFirstEntry($searchResult)
{
return ldap_first_entry($this->resource, $searchResult);
}
/**
* Retrieves the next entry from a search result.
* @param resource $entry link identifier
* @return resource
*/
public function getNextEntry($entry)
{
return ldap_next_entry($this->resource, $entry);
}
/**
* Retrieves the ldap first entry attribute.
* @param resource $entry
* @return string
*/
public function getFirstAttribute($entry)
{
return ldap_first_attribute($this->resource, $entry);
}
/**
* Retrieves the ldap next entry attribute.
* @param resource $entry
* @return string
*/
public function getNextAttribute($entry)
{
return ldap_next_attribute($this->resource, $entry);
}
/**
* Retrieves the ldap entry's attributes.
* @param resource $entry
* @return array
*/
public function getAttributes($entry)
{
return ldap_get_attributes($this->resource, $entry);
}
/**
* Retrieves all binary values from a result entry.
* @param resource $entry link identifier
* @param string $attribute name of attribute
* @return array
*/
public function getValuesLen($entry, $attribute)
{
return ldap_get_values_len($this->resource, $entry, $attribute);
}
/**
* Retrieves the DN of a result entry.
* @param resource $entry
* @return string
*/
public function getDn($entry)
{
return ldap_get_dn($this->resource, $entry);
}
/**
* Free result memory.
* @param resource $searchResult
* @return bool
*/
public function freeResult($searchResult)
{
return ldap_free_result($searchResult);
}
/**
* Sets an option on the current connection.
* @param int $option
* @param mixed $value
* @return boolean
*/
public function setOption($option, $value)
{
return ldap_set_option($this->resource, $option, $value);
}
/**
* Starts a connection using TLS.
* @return bool
*/
public function startTLS()
{
return ldap_start_tls($this->resource);
}
/**
* Send LDAP pagination control.
* @param int $pageSize
* @param bool $isCritical
* @param string $cookie
* @return bool
*/
public function setControlPagedResult($cookie)
{
return ldap_control_paged_result($this->resource, $this->pageSize, false, $cookie);
}
/**
* Retrieve a paginated result response.
* @param resource $result
* @param string $cookie
* @return bool
*/
public function setControlPagedResultResponse($result, &$cookie)
{
return ldap_control_paged_result_response($this->resource, $result, $cookie);
}
/**
* Retrieve the last error on the current connection.
* @return string
*/
public function getLastError()
{
return ldap_error($this->resource);
}
/**
* Returns the number of the last error on the current connection.
* @return int
*/
public function getErrNo()
{
return ldap_errno($this->resource);
}
/**
* Returns the error string of the specified error number.
* @param int $number
* @return string
*/
public function err2Str($number)
{
return ldap_err2str($number);
}
}