-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
ds_ldap.php
2526 lines (2022 loc) · 79.9 KB
/
ds_ldap.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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Classes and functions for communication of Data Stores
*
* @author The phpLDAPadmin development team
* @package phpLDAPadmin
*/
/**
* This abstract class provides the basic variables and methods for LDAP datastores
*
* @package phpLDAPadmin
* @subpackage DataStore
*/
class ldap extends DS {
# If we fail to connect, set this to true
private $noconnect = false;
# Raw Schema entries
private $_schema_entries = null;
# Schema DN
private $_schemaDN = null;
public function __construct($index) {
if (defined('DEBUG_ENABLED') && DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$this->index = $index;
$this->type = 'ldap';
# Additional values that can go in our config.php
$this->custom = new StdClass;
$this->default = new StdClass;
/*
* Not used by PLA
# Database Server Variables
$this->default->server['db'] = array(
'desc'=>'Database Name',
'untested'=>true,
'default'=>null);
*/
/* This was created for IDS - since it doesnt present STRUCTURAL against objectClasses
* definitions when reading the schema.*/
$this->default->server['schema_oclass_default'] = array(
'desc'=>'When reading the schema, and it doesnt specify objectClass type, default it to this',
'default'=>null);
$this->default->server['base'] = array(
'desc'=>'LDAP Base DNs',
'default'=>array());
$this->default->server['tls'] = array(
'desc'=>'Connect using TLS',
'default'=>false);
$this->default->server['tls_cacert'] = array(
'desc'=>'TLS Certificate Authority',
'default'=>null);
$this->default->server['tls_cacertdir'] = array(
'desc'=>'TLS Certificate Authority Directory',
'default'=>null);
$this->default->server['tls_cert'] = array(
'desc'=>'TLS Client Certificate',
'default'=>null);
$this->default->server['tls_key'] = array(
'desc'=>'TLS Client Certificate Key',
'default'=>null);
# Login Details
$this->default->login['attr'] = array(
'desc'=>'Attribute to use to find the users DN',
'default'=>'dn');
$this->default->login['anon_bind'] = array(
'desc'=>'Enable anonymous bind logins',
'default'=>true);
$this->default->login['allowed_dns'] = array(
'desc'=>'Limit logins to users who match any of the following LDAP filters',
'default'=>array());
$this->default->login['base'] = array(
'desc'=>'Limit logins to users who are in these base DNs',
'default'=>array());
$this->default->login['class'] = array(
'desc'=>'Strict login to users containing a specific objectClasses',
'default'=>array());
$this->default->proxy['attr'] = array(
'desc'=>'Attribute to use to find the users DN for proxy based authentication',
'default'=>array());
# SASL configuration
$this->default->sasl['mech'] = array(
'desc'=>'SASL mechanism used while binding LDAP server',
'default'=>'GSSAPI');
$this->default->sasl['realm'] = array(
'desc'=>'SASL realm name',
'untested'=>true,
'default'=>null);
$this->default->sasl['authz_id'] = array(
'desc'=>'SASL authorization id',
'untested'=>true,
'default'=>null);
$this->default->sasl['authz_id_regex'] = array(
'desc'=>'SASL authorization id PCRE regular expression',
'untested'=>true,
'default'=>null);
$this->default->sasl['authz_id_replacement'] = array(
'desc'=>'SASL authorization id PCRE regular expression replacement string',
'untested'=>true,
'default'=>null);
$this->default->sasl['props'] = array(
'desc'=>'SASL properties',
'untested'=>true,
'default'=>null);
}
/**
* Set LDAP option with error checking...
*
* @param resource Connection resource
* @param string Name of option to set
* @param mixed Option value
* @return boolean false if error
*/
private function setLdapOption($resource, $option, $value) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',16,0,__FILE__,__LINE__,__METHOD__,$fargs);
if (! defined($option)) {
system_message(array(
'title'=>sprintf('%s',_('Undefined LDAP option')),
'body'=>sprintf('<b>%s</b>: %s <b>%s</b>',_('Error'),_('Required LDAP option not defined'),$option),
'type'=>'error'));
return false;
}
if (! @ldap_set_option($resource,constant($option),$value)) {
system_message(array(
'title'=>sprintf('%s',_('Failed to set LDAP option')),
'body'=>sprintf('<b>%s</b>: %s <b>%s</b>',_('Error'),_('Failed to set LDAP option'),$option),
'type'=>'error'));
return false;
}
return true;
}
/**
* Required ABSTRACT functions
*/
/**
* Connect and Bind to the Database
*
* @param string Which connection method resource to use
* @return resource|null Connection resource if successful, null if not.
*/
protected function connect($method,$debug=false,$new=false) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
static $CACHE = array();
$method = $this->getMethod($method);
$bind = array();
if (isset($CACHE[$this->index][$method]) && $CACHE[$this->index][$method])
return $CACHE[$this->index][$method];
# Check if we have logged in and therefore need to use those details as our bind.
$bind['id'] = is_null($this->getLogin($method)) && $method != 'anon' ? $this->getLogin('user') : $this->getLogin($method);
$bind['pass'] = is_null($this->getPassword($method)) && $method != 'anon' ? $this->getPassword('user') : $this->getPassword($method);
# If our bind id is still null, we are not logged in.
if (is_null($bind['id']) && ! in_array($method,array('anon','login')))
return null;
# If we bound to the LDAP server with these details for a different connection, return that resource
if (isset($CACHE[$this->index]) && ! $new)
foreach ($CACHE[$this->index] as $cachedmethod => $resource) {
if (($this->getLogin($cachedmethod) == $bind['id']) && ($this->getPassword($cachedmethod) == $bind['pass'])) {
$CACHE[$this->index][$method] = $resource;
return $CACHE[$this->index][$method];
}
}
$CACHE[$this->index][$method] = null;
# No identifiable connection exists, lets create a new one.
if (DEBUG_ENABLED)
debug_log('Creating NEW connection [%s] for index [%s]',16,0,__FILE__,__LINE__,__METHOD__,
$method,$this->index);
if (function_exists('run_hook'))
run_hook('pre_connect',array('server_id'=>$this->index,'method'=>$method));
if ($this->getValue('server','port'))
$resource = ldap_connect($this->getValue('server','host'),$this->getValue('server','port'));
else
$resource = ldap_connect($this->getValue('server','host'));
$this->noconnect = false;
$CACHE[$this->index][$method] = $resource;
if (DEBUG_ENABLED)
debug_log('LDAP Resource [%s], Host [%s], Port [%s]',16,0,__FILE__,__LINE__,__METHOD__,
$resource,$this->getValue('server','host'),$this->getValue('server','port'));
if (!$resource)
debug_dump_backtrace('UNHANDLED, $resource is not a resource',1);
# Go with LDAP version 3 if possible (needed for renaming and Novell schema fetching)
if (! $this->setLdapOption($resource,'LDAP_OPT_PROTOCOL_VERSION',3))
$this->noconnect = true;
/* Disabling this makes it possible to browse the tree for Active Directory, and seems
* to not affect other LDAP servers (tested with OpenLDAP) as phpLDAPadmin explicitly
* specifies deref behavior for each ldap_search operation. */
elseif (! $this->setLdapOption($resource,'LDAP_OPT_REFERRALS',0))
$this->noconnect = true;
/* Enabling manageDsaIt to be able to browse through glued entries
* 2.16.840.1.113730.3.4.2 : "ManageDsaIT Control" "RFC 3296" "The client may provide
* the ManageDsaIT control with an operation to indicate that the operation is intended
* to manage objects within the DSA (server) Information Tree. The control causes
* Directory-specific entries (DSEs), regardless of type, to be treated as normal entries
* allowing clients to interrogate and update these entries using LDAP operations." */
elseif (! $this->setLdapOption($resource,'LDAP_OPT_SERVER_CONTROLS',array(array('oid'=>'2.16.840.1.113730.3.4.2'))))
$this->noconnect = true;
# Try to fire up TLS is specified in the config
if ($this->isTLSEnabled() && !$this->noconnect)
if(! $this->startTLS($resource))
$this->noconnect = true;
# If SASL has been configured for binding, then start it now.
if ($this->noconnect)
$bind['result'] = false;
elseif ($this->isSASLEnabled())
$bind['result'] = $this->startSASL($resource,$method,$bind['id'],$bind['pass']);
# Normal bind...
else
$bind['result'] = @ldap_bind($resource,$bind['id'],$bind['pass']);
if ($debug)
debug_dump(array('method'=>$method,'bind'=>$bind,'USER'=>$_SESSION['USER']));
if (DEBUG_ENABLED)
debug_log('Resource [%s], Bind Result [%s]',16,0,__FILE__,__LINE__,__METHOD__,$resource,$bind);
if (! $bind['result']) {
if (DEBUG_ENABLED)
debug_log('Leaving with FALSE, bind FAILed',16,0,__FILE__,__LINE__,__METHOD__);
if (! $this->noconnect) {
$this->noconnect = true;
system_message(array(
'title'=>sprintf('%s %s',_('Unable to connect to LDAP server'),$this->getName()),
'body'=>sprintf('<b>%s</b>: %s (%s) for <b>%s</b>',_('Error'),$this->getErrorMessage($method),$this->getErrorNum($method),$method),
'type'=>'error'));
}
$CACHE[$this->index][$method] = null;
} else {
# If this is a proxy session, we need to switch to the proxy user
if ($this->isProxyEnabled() && $bind['id'] && $method != 'anon')
if (! $this->startProxy($resource,$method)) {
$this->noconnect = true;
$CACHE[$this->index][$method] = null;
}
}
if (function_exists('run_hook'))
run_hook('post_connect',array('server_id'=>$this->index,'method'=>$method,'id'=>$bind['id']));
if ($debug)
debug_dump(array($method=>$CACHE[$this->index][$method]));
return $CACHE[$this->index][$method];
}
/**
* Login to the database with the application user/password
*
* @return boolean true|false for successful login.
*/
public function login($user=null,$pass=null,$method=null,$new=false) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$userDN = null;
# Get the userDN from the username.
if (! is_null($user)) {
# If login,attr is set to DN, then user should be a DN
if (($this->getValue('login','attr') == 'dn') || $method != 'user')
$userDN = $this->getValue('login', 'bind_dn_template') ? $this->fillDNTemplate($user) : $user;
else
$userDN = $this->getLoginID($user,'login');
if (! $userDN && $this->getValue('login','fallback_dn') && strpos($user, '='))
$userDN = $user;
if (! $userDN)
return false;
} else {
if (in_array($method,array('user','anon'))) {
$method = 'anon';
$userDN = '';
$pass = '';
} else {
$userDN = $this->getLogin('user');
$pass = $this->getPassword('user');
}
}
if (! $this->isAnonBindAllowed() && ! trim($userDN))
return false;
# Temporarily set our user details
$this->setLogin($userDN,$pass,$method);
$connect = $this->connect($method,false,$new);
# If we didnt log in...
if (!$connect || $this->noconnect || ! $this->userIsAllowedLogin($userDN)) {
$this->logout($method);
return false;
} else
return true;
}
/**
* Perform a query to the Database
*
* @param string query to perform
* $query['base']
* $query['filter']
* $query['scope']
* $query['attrs'] = array();
* $query['deref']
* @param string Which connection method resource to use
* @param string Index items according to this key
* @param boolean Enable debugging output
* @return array|null Results of query.
*/
public function query($query,$method,$index=null,$debug=false) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$attrs_only = 0;
# Defaults
if (! isset($query['attrs']))
$query['attrs'] = array();
else
# Re-index the attrs, PHP throws an error if the keys are not sequential from 0.
$query['attrs'] = array_values($query['attrs']);
if (! isset($query['base'])) {
$bases = $this->getBaseDN();
$query['base'] = array_shift($bases);
}
if (! isset($query['deref']))
$query['deref'] = $_SESSION[APPCONFIG]->getValue('deref','search');
if (! isset($query['filter']))
$query['filter'] = '(&(objectClass=*))';
if (! isset($query['scope']))
$query['scope'] = 'sub';
if (! isset($query['size_limit']))
$query['size_limit'] = 0;
if (! isset($query['time_limit']))
$query['time_limit'] = 0;
if ($query['scope'] == 'base' && ! isset($query['baseok']))
system_message(array(
'title'=>sprintf('Dont call %s',__METHOD__),
'body'=>sprintf('Use getDNAttrValues for base queries [%s]',$query['base']),
'type'=>'info'));
if (is_array($query['base'])) {
system_message(array(
'title'=>_('Invalid BASE for query'),
'body'=>_('The query was cancelled because of an invalid base.'),
'type'=>'error'));
return array();
}
if (DEBUG_ENABLED)
debug_log('%s search PREPARE.',16,0,__FILE__,__LINE__,__METHOD__,$query['scope']);
if ($debug)
debug_dump(array('query'=>$query,'server'=>$this->getIndex(),'con'=>$this->connect($method)));
$search = null;
$resource = $this->connect($method,$debug);
if ($resource)
switch ($query['scope']) {
case 'base':
$search = @ldap_read($resource,$query['base'],$query['filter'],$query['attrs'],$attrs_only,$query['size_limit'],$query['time_limit'],$query['deref']);
break;
case 'one':
$search = @ldap_list($resource,$query['base'],$query['filter'],$query['attrs'],$attrs_only,$query['size_limit'],$query['time_limit'],$query['deref']);
break;
case 'sub':
default:
$search = @ldap_search($resource,$query['base'],$query['filter'],$query['attrs'],$attrs_only,$query['size_limit'],$query['time_limit'],$query['deref']);
break;
}
if ($debug)
debug_dump(array('method'=>$method,'search'=>$search,'error'=>$this->getErrorMessage()));
if (DEBUG_ENABLED)
debug_log('Search scope [%s] base [%s] filter [%s] attrs [%s] COMPLETE (%s).',16,0,__FILE__,__LINE__,__METHOD__,
$query['scope'],$query['base'],$query['filter'],$query['attrs'],is_null($search));
if (! $search)
return array();
$return = array();
# Get the first entry identifier
if ($entries = ldap_get_entries($resource,$search)) {
# Remove the count
if (isset($entries['count']))
unset($entries['count']);
# Iterate over the entries
foreach ($entries as $a => $entry) {
if (! isset($entry['dn']))
debug_dump_backtrace('No DN?',1);
# Remove the none entry references.
if (! is_array($entry)) {
unset($entries[$a]);
continue;
}
$dn = $entry['dn'];
unset($entry['dn']);
# Iterate over the attributes
foreach ($entry as $b => $attrs) {
# Remove the none entry references.
if (! is_array($attrs)) {
unset($entry[$b]);
continue;
}
# Remove the count
if (isset($entry[$b]['count']))
unset($entry[$b]['count']);
}
# Our queries always include the DN (the only value not an array).
$entry['dn'] = $dn;
$return[$dn] = $entry;
}
# Sort our results
foreach ($return as $key=> $values)
ksort($return[$key]);
}
if (DEBUG_ENABLED)
debug_log('Returning (%s)',17,0,__FILE__,__LINE__,__METHOD__,$return);
return $return;
}
/**
* Get the last error string
*
* @param string Which connection method resource to use
*/
public function getErrorMessage($method=null) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
return ldap_error($this->connect($method));
}
/**
* Get the last error number
*
* @param string Which connection method resource to use
*/
public function getErrorNum($method=null) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
return ldap_errno($this->connect($method));
}
/**
* Additional functions
*/
/**
* Get a user ID
*
* @param string Which connection method resource to use
*/
public function getLoginID($user,$method=null) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$query['filter'] = sprintf('(&(%s=%s)%s)',
$this->getValue('login','attr'),$user,
$this->getLoginClass() ? sprintf('(objectclass=%s)',join(')(objectclass=',$this->getLoginClass())) : '');
$query['attrs'] = array('dn');
$result = array();
foreach ($this->getLoginBaseDN() as $base) {
$query['base'] = $base;
$result = $this->query($query,$method);
if (count($result) == 1)
break;
}
if (count($result) != 1)
return null;
$detail = array_shift($result);
if (! isset($detail['dn']))
die('ERROR: DN missing?');
else
return $detail['dn'];
}
/**
* Return the login base DNs
* If no login base DNs are defined, then the LDAP server Base DNs are used.
*/
private function getLoginBaseDN() {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,1,__FILE__,__LINE__,__METHOD__,$fargs);
if ($this->getValue('login','base'))
return $this->getValue('login','base');
else
return $this->getBaseDN();
}
private function fillDNTemplate($user) {
foreach($this->getLoginBaseDN() as $base)
if(substr_compare($user, $base, -strlen($base)) === 0)
return $user; // $user already passed as DN
// fill template
return sprintf($this->getValue('login', 'bind_dn_template'), preg_replace('/([,\\\\#+<>;"=])/', '\\\\$1', $user));
}
/**
* Return the login classes that a user must have to login
*/
private function getLoginClass() {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,1,__FILE__,__LINE__,__METHOD__,$fargs);
return $this->getValue('login','class');
}
/**
* Return if anonymous bind is allowed in the configuration
*/
public function isAnonBindAllowed() {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
return $this->getValue('login','anon_bind');
}
/**
* Fetches whether TLS has been configured for use with a certain server.
*
* Users may configure phpLDAPadmin to use TLS in config,php thus:
* <code>
* $servers->setValue('server','tls',true|false);
* </code>
*
* @return boolean
*/
private function isTLSEnabled() {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
if ($this->getValue('server','tls') && ! function_exists('ldap_start_tls')) {
error(_('TLS has been enabled in your config, but your PHP install does not support TLS. TLS will be disabled.'),'warn');
return false;
} else
return $this->getValue('server','tls');
}
/**
* If TLS is configured, then start it
*/
private function startTLS($resource) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
// LDAP_OPT_X_TLS_ options must be set globally ($res = null)
// until LDAP_OPT_X_TLS_NEWCTX is exported,
// NOTE: new values will require php-fpm or other stateful
// php servers to be restarted, and are global for all php
// users in the process pool!
$val = $this->getValue('server','tls_cacert');
if (! empty($val))
if (! $this->setLdapOption(null, 'LDAP_OPT_X_TLS_CACERTFILE', $val))
return false;
$val = $this->getValue('server','tls_cacertdir');
if (! empty($val))
if (! $this->setLdapOption(null, 'LDAP_OPT_X_TLS_CACERTDIR', $val))
return false;
$val = $this->getValue('server','tls_cert');
if (! empty($val))
if (! $this->setLdapOption(null, 'LDAP_OPT_X_TLS_CERTFILE', $val))
return false;
$val = $this->getValue('server','tls_key');
if (! empty($val))
if (! $this->setLdapOption(null, 'LDAP_OPT_X_TLS_KEYFILE', $val))
return false;
if (! @ldap_start_tls($resource)) {
$diag_error='';
ldap_get_option($resource, LDAP_OPT_DIAGNOSTIC_MESSAGE, $diag_error);
if (! empty($diag_error)) {
$diag_error = '<br>'.$diag_error;
}
$error = ldap_error($resource);
system_message(array(
'title'=>sprintf('%s (%s)',_('Could not start TLS.'),$this->getName()),
'body'=>sprintf('<b>%s</b>: %s %s%s',_('Error'),_('Could not start TLS.'),$error,$diag_error),
'type'=>'error'));
return false;
} else
return true;
}
/**
* Fetches whether SASL has been configured for use with a certain server.
*
* Users may configure phpLDAPadmin to use SASL in config,php thus:
* <code>
* $servers->setValue('login','auth_type','sasl');
* OR
* $servers->setValue('sasl','mech','PLAIN');
* OR
* $servers->setValue('login','auth_type','sasl_external');
* </code>
*
* @return boolean
*/
private function isSASLEnabled() {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
if (! in_array($this->getValue('login','auth_type'), array('sasl','sasl_external'))) {
// check if SASL mech uses login from other auth_types
if (! in_array(strtolower($this->getValue('sasl', 'mech')), array('plain')))
return false;
}
if (! function_exists('ldap_sasl_bind')) {
error(_('SASL has been enabled in your config, but your PHP install does not support SASL. SASL will be disabled.'),'warn');
return false;
}
# If we get here, SASL must be configured.
return true;
}
/**
* If SASL is configured, then start it
* To be able to use SASL, PHP should have been compliled with --with-ldap-sasl=DIR
*
* @todo This has not been tested, please let the developers know if this function works as expected.
*/
private function startSASL($resource,$method,$login,$pass) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
static $CACHE = array();
# We shouldnt be doing SASL binds for anonymous queries?
if ($method == 'anon')
return false;
# EXTERNAL mech is really a different authType
if ($this->getAuthType() == 'sasl_external') {
return @ldap_sasl_bind($resource,NULL,NULL,
'EXTERNAL',NULL,NULL,
$this->getValue('sasl','props'));
}
# At the moment, we have only implemented GSSAPI and PLAIN
if (! in_array(strtolower($this->getValue('sasl','mech')),array('gssapi','plain'))) {
system_message(array(
'title'=>_('SASL Method not implemented'),
'body'=>sprintf('<b>%s</b>: %s %s',_('Error'),$this->getValue('sasl','mech'),_('has not been implemented yet')),
'type'=>'error'));
return false;
}
if (strtolower($this->getValue('sasl','mech')) == 'plain') {
return @ldap_sasl_bind($resource,NULL,$pass,'PLAIN',
$this->getValue('sasl','realm'),
$login,
$this->getValue('sasl','props'));
}
if (! isset($CACHE['login_dn']))
$CACHE['login_dn'] = $login;
$CACHE['authz_id'] = '';
/*
# Do we need to rewrite authz_id?
if (! isset($CACHE['authz_id']))
if (! trim($this->getValue('sasl','authz_id')) && strtolower($this->getValue('sasl','mech')) != 'gssapi') {
if (DEBUG_ENABLED)
debug_log('Rewriting bind DN [%s] -> authz_id with regex [%s] and replacement [%s].',9,0,__FILE__,__LINE__,__METHOD__,
$CACHE['login_dn'],
$this->getValue('sasl','authz_id_regex'),
$this->getValue('sasl','authz_id_replacement'));
$CACHE['authz_id'] = @preg_replace($this->getValue('sasl','authz_id_regex'),
$this->getValue('sasl','authz_id_replacement'),$CACHE['login_dn']);
# Invalid regex?
if (is_null($CACHE['authz_id']))
error(sprintf(_('It seems that sasl_authz_id_regex "%s" contains invalid PCRE regular expression. The error is "%s".'),
$this->getValue('sasl','authz_id_regex'),(isset($php_errormsg) ? $php_errormsg : '')),
'error','index.php');
if (DEBUG_ENABLED)
debug_log('Resource [%s], SASL OPTIONS: mech [%s], realm [%s], authz_id [%s], props [%s]',9,0,__FILE__,__LINE__,__METHOD__,
$resource,
$this->getValue('sasl','mech'),
$this->getValue('sasl','realm'),
$CACHE['authz_id'],
$this->getValue('sasl','props'));
} else
$CACHE['authz_id'] = $this->getValue('sasl','authz_id');
*/
# @todo this function is different in PHP5.1 and PHP5.2
return @ldap_sasl_bind($resource,NULL,'',
$this->getValue('sasl','mech'),
$this->getValue('sasl','realm'),
$CACHE['authz_id'],
$this->getValue('sasl','props'));
}
/**
* Fetches whether PROXY AUTH has been configured for use with a certain server.
*
* Users may configure phpLDAPadmin to use PROXY AUTH in config,php thus:
* <code>
* $servers->setValue('login','auth_type','proxy');
* </code>
*
* @return boolean
*/
private function isProxyEnabled() {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
return $this->getValue('login','auth_type') == 'proxy' ? true : false;
}
/**
* If PROXY AUTH is configured, then start it
*/
private function startProxy($resource,$method) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$rootdse = $this->getRootDSE();
if (! (isset($rootdse['supportedcontrol']) && in_array('2.16.840.1.113730.3.4.18',$rootdse['supportedcontrol']))) {
system_message(array(
'title'=>sprintf('%s %s',_('Unable to start proxy connection'),$this->getName()),
'body'=>sprintf('<b>%s</b>: %s',_('Error'),_('Your LDAP server doesnt seem to support this control')),
'type'=>'error'));
return false;
}
$filter = '(&';
$dn = '';
$missing = false;
foreach ($this->getValue('proxy','attr') as $attr => $var) {
if (! isset($_SERVER[$var])) {
system_message(array(
'title'=>sprintf('%s %s',_('Unable to start proxy connection'),$this->getName()),
'body'=>sprintf('<b>%s</b>: %s (%s)',_('Error'),_('Attribute doesnt exist'),$var),
'type'=>'error'));
$missing = true;
} else {
if ($attr == 'dn') {
$dn = $var;
break;
} else
$filter .= sprintf('(%s=%s)',$attr,$_SERVER[$var]);
}
}
if ($missing)
return false;
$filter .= ')';
if (! $dn) {
$query['filter'] = $filter;
foreach ($this->getBaseDN() as $base) {
$query['base'] = $base;
if ($search = $this->query($query,$method))
break;
}
if (count($search) != 1) {
system_message(array(
'title'=>sprintf('%s %s',_('Unable to start proxy connection'),$this->getName()),
'body'=>sprintf('<b>%s</b>: %s (%s)',_('Error'),_('Search for DN returned the incorrect number of results'),count($search)),
'type'=>'error'));
return false;
}
$search = array_pop($search);
$dn = $search['dn'];
}
$ctrl = array(
'oid'=>'2.16.840.1.113730.3.4.18',
'value'=>sprintf('dn:%s',$dn),
'iscritical' => true);
if (! @ldap_set_option($resource,LDAP_OPT_SERVER_CONTROLS,array($ctrl))) {
system_message(array(
'title'=>sprintf('%s %s',_('Unable to start proxy connection'),$this->getName()),
'body'=>sprintf('<b>%s</b>: %s (%s) for <b>%s</b>',_('Error'),$this->getErrorMessage($method),$this->getErrorNum($method),$method),
'type'=>'error'));
return false;
}
$_SESSION['USER'][$this->index][$method]['proxy'] = blowfish_encrypt($dn);
return true;
}
/**
* Modify attributes of a DN
*/
public function modify($dn,$attrs,$method=null) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
# We need to supress the error here - programming should detect and report it.
return @ldap_mod_replace($this->connect($method),$dn,$attrs);
}
/**
* Gets the root DN of the specified LDAPServer, or null if it
* can't find it (ie, the server won't give it to us, or it isnt
* specified in the configuration file).
*
* Tested with OpenLDAP 2.0, Netscape iPlanet, and Novell eDirectory 8.7 (nldap.com)
* Please report any and all bugs!!
*
* Please note: On FC systems, it seems that php_ldap uses /etc/openldap/ldap.conf in
* the search base if it is blank - so edit that file and comment out the BASE line.
*
* @param string Which connection method resource to use
* @return array dn|null The root DN of the server on success (string) or null on error.
* @todo Sort the entries, so that they are in the correct DN order.
*/
public function getBaseDN($method=null) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
static $CACHE;
$method = $this->getMethod($method);
$result = array();
if (isset($CACHE[$this->index][$method]))
return $CACHE[$this->index][$method];
# If the base is set in the configuration file, then just return that.
if (count($this->getValue('server','base'))) {
if (DEBUG_ENABLED)
debug_log('Return BaseDN from Config [%s]',17,0,__FILE__,__LINE__,__METHOD__,implode('|',$this->getValue('server','base')));
$CACHE[$this->index][$method] = $this->getValue('server','base');
# We need to figure it out.
} else {
if (DEBUG_ENABLED)
debug_log('Connect to LDAP to find BaseDN',80,0,__FILE__,__LINE__,__METHOD__);
# Set this to empty, in case we loop back here looking for the baseDNs
$CACHE[$this->index][$method] = array();
$results = $this->getDNAttrValues('',$method);
if (isset($results['namingcontexts'])) {
if (DEBUG_ENABLED)
debug_log('LDAP Entries:%s',80,0,__FILE__,__LINE__,__METHOD__,implode('|',$results['namingcontexts']));
$result = $results['namingcontexts'];
}
$CACHE[$this->index][$method] = $result;
}
return $CACHE[$this->index][$method];
}
/**
* Gets whether an entry exists based on its DN. If the entry exists,
* returns true. Otherwise returns false.
*
* @param string The DN of the entry of interest.
* @param string Which connection method resource to use
* @return boolean
*/
public function dnExists($dn,$method=null) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$results = $this->getDNAttrValues($dn,$method);
if ($results)
return $results;
else
return false;
}
/**
* Given a DN string, this returns the top container portion of the string.
*
* @param string The DN whose container string to return.
* @return string The container
*/
public function getContainerTop($dn) {
if (DEBUG_ENABLED && (($fargs=func_get_args())||$fargs='NOARGS'))
debug_log('Entered (%%)',17,0,__FILE__,__LINE__,__METHOD__,$fargs);
$return = $dn;
foreach ($this->getBaseDN() as $base) {
if (preg_match("/${base}$/i",$dn)) {
$return = $base;
break;
}
}
if (DEBUG_ENABLED)