abook_ldap_server.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. /**
  3. * abook_ldap_server.php
  4. *
  5. * Copyright (c) 1999-2005 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * Address book backend for LDAP server
  9. *
  10. * LDAP filtering code by Tim Bell
  11. * <bhat at users.sourceforge.net> (#539534)
  12. * ADS limit_scope code by Michael Brown
  13. * <mcb30 at users.sourceforge.net> (#1035454)
  14. * StartTLS code by John Lane
  15. * <starfry at users.sourceforge.net> (#1197703)
  16. *
  17. * @version $Id$
  18. * @package squirrelmail
  19. * @subpackage addressbook
  20. */
  21. /**
  22. * Address book backend for LDAP server
  23. *
  24. * An array with the following elements must be passed to
  25. * the class constructor (elements marked ? are optional)
  26. *
  27. * Main settings:
  28. * <pre>
  29. * host => LDAP server hostname/IP-address
  30. * base => LDAP server root (base dn). Empty string allowed.
  31. * ? port => LDAP server TCP port number (default: 389)
  32. * ? charset => LDAP server charset (default: utf-8)
  33. * ? name => Name for LDAP server (default "LDAP: hostname")
  34. * Used to tag the result data
  35. * ? maxrows => Maximum # of rows in search result
  36. * ? timeout => Timeout for LDAP operations (in seconds, default: 30)
  37. * Might not work for all LDAP libraries or servers.
  38. * ? binddn => LDAP Bind DN.
  39. * ? bindpw => LDAP Bind Password.
  40. * ? protocol => LDAP Bind protocol.
  41. * </pre>
  42. * Advanced settings:
  43. * <pre>
  44. * ? filter => Filter expression to limit ldap searches
  45. * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
  46. * ? listing => Controls listing of LDAP directory.
  47. * ? search_tree => Controls subtree or one level search.
  48. * ? starttls => Controls use of StartTLS on LDAP connections
  49. * </pre>
  50. * NOTE. This class should not be used directly. Use the
  51. * "AddressBook" class instead.
  52. * @package squirrelmail
  53. * @subpackage addressbook
  54. */
  55. class abook_ldap_server extends addressbook_backend {
  56. /**
  57. * @var string backend type
  58. */
  59. var $btype = 'remote';
  60. /**
  61. * @var string backend name
  62. */
  63. var $bname = 'ldap_server';
  64. /* Parameters changed by class */
  65. /**
  66. * @var string displayed name
  67. */
  68. var $sname = 'LDAP'; /* Service name */
  69. /**
  70. * @var string LDAP server name or address or url
  71. */
  72. var $server = '';
  73. /**
  74. * @var integer LDAP server port
  75. */
  76. var $port = 389;
  77. /**
  78. * @var string LDAP base DN
  79. */
  80. var $basedn = '';
  81. /**
  82. * @var string charset used for entries in LDAP server
  83. */
  84. var $charset = 'utf-8';
  85. /**
  86. * @var object PHP LDAP link ID
  87. */
  88. var $linkid = false;
  89. /**
  90. * @var bool True if LDAP server is bound
  91. */
  92. var $bound = false;
  93. /**
  94. * @var integer max rows in result
  95. */
  96. var $maxrows = 250;
  97. /**
  98. * @var string ldap filter
  99. * @since 1.5.1
  100. */
  101. var $filter = '';
  102. /**
  103. * @var integer timeout of LDAP operations (in seconds)
  104. */
  105. var $timeout = 30;
  106. /**
  107. * @var string DN to bind to (non-anonymous bind)
  108. * @since 1.5.0 and 1.4.3
  109. */
  110. var $binddn = '';
  111. /**
  112. * @var string password to bind with (non-anonymous bind)
  113. * @since 1.5.0 and 1.4.3
  114. */
  115. var $bindpw = '';
  116. /**
  117. * @var integer protocol used to connect to ldap server
  118. * @since 1.5.0 and 1.4.3
  119. */
  120. var $protocol = '';
  121. /**
  122. * @var boolean limits scope to base dn
  123. * @since 1.5.1
  124. */
  125. var $limit_scope = false;
  126. /**
  127. * @var boolean controls listing of directory
  128. * @since 1.5.1
  129. */
  130. var $listing = false;
  131. /**
  132. * @var boolean controls ldap search type.
  133. * only first level entries are displayed if set to false
  134. * @since 1.5.1
  135. */
  136. var $search_tree = true;
  137. /**
  138. * @var boolean controls use of StartTLS on ldap
  139. * connections. Requires php 4.2+ and protocol >= 3
  140. * @since 1.5.1
  141. */
  142. var $starttls = false;
  143. /**
  144. * Constructor. Connects to database
  145. * @param array connection options
  146. */
  147. function abook_ldap_server($param) {
  148. if(!function_exists('ldap_connect')) {
  149. $this->set_error(_("PHP install does not have LDAP support."));
  150. return;
  151. }
  152. if(is_array($param)) {
  153. $this->server = $param['host'];
  154. $this->basedn = $param['base'];
  155. if(!empty($param['port']))
  156. $this->port = $param['port'];
  157. if(!empty($param['charset']))
  158. $this->charset = strtolower($param['charset']);
  159. if(isset($param['maxrows']))
  160. $this->maxrows = $param['maxrows'];
  161. if(isset($param['timeout']))
  162. $this->timeout = $param['timeout'];
  163. if(isset($param['binddn']))
  164. $this->binddn = $param['binddn'];
  165. if(isset($param['bindpw']))
  166. $this->bindpw = $param['bindpw'];
  167. if(isset($param['protocol']))
  168. $this->protocol = (int) $param['protocol'];
  169. if(isset($param['filter']))
  170. $this->filter = trim($param['filter']);
  171. if(isset($param['limit_scope']))
  172. $this->limit_scope = (bool) $param['limit_scope'];
  173. if(isset($param['listing']))
  174. $this->listing = (bool) $param['listing'];
  175. if(isset($param['search_tree']))
  176. $this->search_tree = (bool) $param['search_tree'];
  177. if(isset($param['starttls']))
  178. $this->starttls = (bool) $param['starttls'];
  179. if(empty($param['name'])) {
  180. $this->sname = 'LDAP: ' . $param['host'];
  181. } else {
  182. $this->sname = $param['name'];
  183. }
  184. /*
  185. * don't open LDAP server on addressbook_init(),
  186. * open ldap connection only on search. Speeds up
  187. * addressbook_init() call.
  188. */
  189. // $this->open(true);
  190. } else {
  191. $this->set_error('Invalid argument to constructor');
  192. }
  193. }
  194. /**
  195. * Open the LDAP server.
  196. * @param bool $new is it a new connection
  197. * @return bool
  198. */
  199. function open($new = false) {
  200. $this->error = '';
  201. /* Connection is already open */
  202. if($this->linkid != false && !$new) {
  203. return true;
  204. }
  205. $this->linkid = @ldap_connect($this->server, $this->port);
  206. /**
  207. * check if connection was successful
  208. * It does not work with OpenLDAP 2.x libraries. Connect error will be
  209. * displayed only on ldap command that tries to make connection
  210. * (ldap_start_tls or ldap_bind).
  211. */
  212. if(!$this->linkid) {
  213. return $this->set_error($this->ldap_error('ldap_connect failed'));
  214. }
  215. if(!empty($this->protocol)) {
  216. // make sure that ldap_set_option() is available before using it
  217. if(! function_exists('ldap_set_option') ||
  218. !@ldap_set_option($this->linkid, LDAP_OPT_PROTOCOL_VERSION, $this->protocol)) {
  219. return $this->set_error('unable to set ldap protocol number');
  220. }
  221. }
  222. /**
  223. * http://www.php.net/ldap-start-tls
  224. * Check if v3 or newer protocol is used,
  225. * check if ldap_start_tls function is available.
  226. * Silently ignore setting, if requirements are not satisfied
  227. */
  228. if($this->starttls &&
  229. !empty($this->protocol) && $this->protocol >= 3 &&
  230. function_exists('ldap_start_tls') ) {
  231. // make sure that $this->host is not ldaps:// URL.
  232. if (preg_match("/^ldaps:\/\/.+/i",$this->server)) {
  233. return $this->set_error("you can't enable starttls on ldaps connection.");
  234. }
  235. // TODO: starttls and ldapi:// tests are needed
  236. // try starting tls
  237. if (! @ldap_start_tls($this->linkid)) {
  238. // set error if call fails
  239. return $this->set_error($this->ldap_error('ldap_start_tls failed'));
  240. }
  241. }
  242. if(!empty($this->limit_scope) && $this->limit_scope) {
  243. if(empty($this->protocol) || intval($this->protocol) < 3) {
  244. return $this->set_error('limit_scope requires protocol >= 3');
  245. }
  246. // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
  247. $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
  248. /*
  249. * Option is set only during connection.
  250. * It does not cause immediate errors with OpenLDAP 2.x libraries.
  251. */
  252. if(! function_exists('ldap_set_option') ||
  253. !@ldap_set_option($this->linkid, LDAP_OPT_SERVER_CONTROLS, array($ctrl))) {
  254. return $this->set_error($this->ldap_error('limit domain scope failed'));
  255. }
  256. }
  257. // authenticated bind
  258. if(!empty($this->binddn)) {
  259. if(!@ldap_bind($this->linkid, $this->binddn, $this->bindpw)) {
  260. return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
  261. }
  262. } else {
  263. // anonymous bind
  264. if(!@ldap_bind($this->linkid)) {
  265. return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
  266. }
  267. }
  268. $this->bound = true;
  269. return true;
  270. }
  271. /**
  272. * Encode string to the charset used by this LDAP server
  273. * @param string string that has to be encoded
  274. * @return string encoded string
  275. */
  276. function charset_encode($str) {
  277. global $default_charset;
  278. if($this->charset != $default_charset) {
  279. return charset_convert($default_charset,$str,$this->charset,false);
  280. } else {
  281. return $str;
  282. }
  283. }
  284. /**
  285. * Decode from charset used by this LDAP server to charset used by translation
  286. *
  287. * Uses SquirrelMail charset_decode functions
  288. * @param string string that has to be decoded
  289. * @return string decoded string
  290. */
  291. function charset_decode($str) {
  292. global $default_charset;
  293. if ($this->charset != $default_charset) {
  294. return charset_convert($this->charset,$str,$default_charset,false);
  295. } else {
  296. return $str;
  297. }
  298. }
  299. /**
  300. * Sanitizes ldap search strings.
  301. * See rfc2254
  302. * @link http://www.faqs.org/rfcs/rfc2254.html
  303. * @since 1.5.1 and 1.4.5
  304. * @param string $string
  305. * @return string sanitized string
  306. */
  307. function ldapspecialchars($string) {
  308. $sanitized=array('\\' => '\5c',
  309. '*' => '\2a',
  310. '(' => '\28',
  311. ')' => '\29',
  312. "\x00" => '\00');
  313. return str_replace(array_keys($sanitized),array_values($sanitized),$string);
  314. }
  315. /**
  316. * Search LDAP server.
  317. *
  318. * Warning: You must make sure that ldap query is correctly formated and
  319. * sanitize use of special ldap keywords.
  320. * @param string $expression ldap query
  321. * @return array search results (false on error)
  322. * @since 1.5.1
  323. */
  324. function ldap_search($expression) {
  325. /* Make sure connection is there */
  326. if(!$this->open()) {
  327. return false;
  328. }
  329. if ($this->search_tree) {
  330. // ldap_search - search subtree
  331. $sret = @ldap_search($this->linkid, $this->basedn, $expression,
  332. array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
  333. 0, $this->maxrows, $this->timeout);
  334. } else {
  335. // ldap_list - search one level
  336. $sret = @ldap_list($this->linkid, $this->basedn, $expression,
  337. array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
  338. 0, $this->maxrows, $this->timeout);
  339. }
  340. /* Return error if search failed */
  341. if(!$sret) {
  342. return $this->set_error($this->ldap_error('ldap_search failed'));
  343. }
  344. if(@ldap_count_entries($this->linkid, $sret) <= 0) {
  345. return array();
  346. }
  347. /* Get results */
  348. $ret = array();
  349. $returned_rows = 0;
  350. $res = @ldap_get_entries($this->linkid, $sret);
  351. for($i = 0 ; $i < $res['count'] ; $i++) {
  352. $row = $res[$i];
  353. /* Extract data common for all e-mail addresses
  354. * of an object. Use only the first name */
  355. $nickname = $this->charset_decode($row['dn']);
  356. // TODO: remove basedn from $nickname
  357. $fullname = $this->charset_decode($row['cn'][0]);
  358. if(!empty($row['ou'][0])) {
  359. $label = $this->charset_decode($row['ou'][0]);
  360. }
  361. else if(!empty($row['o'][0])) {
  362. $label = $this->charset_decode($row['o'][0]);
  363. } else {
  364. $label = '';
  365. }
  366. if(empty($row['givenname'][0])) {
  367. $firstname = '';
  368. } else {
  369. $firstname = $this->charset_decode($row['givenname'][0]);
  370. }
  371. if(empty($row['sn'][0])) {
  372. $surname = '';
  373. } else {
  374. $surname = $this->charset_decode($row['sn'][0]);
  375. }
  376. /* Add one row to result for each e-mail address */
  377. if(isset($row['mail']['count'])) {
  378. for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
  379. array_push($ret, array('nickname' => $nickname,
  380. 'name' => $fullname,
  381. 'firstname' => $firstname,
  382. 'lastname' => $surname,
  383. 'email' => $row['mail'][$j],
  384. 'label' => $label,
  385. 'backend' => $this->bnum,
  386. 'source' => &$this->sname));
  387. // Limit number of hits
  388. $returned_rows++;
  389. if(($returned_rows >= $this->maxrows) &&
  390. ($this->maxrows > 0) ) {
  391. ldap_free_result($sret);
  392. return $ret;
  393. }
  394. } // for($j ...)
  395. } // isset($row['mail']['count'])
  396. }
  397. ldap_free_result($sret);
  398. return $ret;
  399. }
  400. /**
  401. * Get error from LDAP resource if possible
  402. *
  403. * Should get error from server using the ldap_errno() and ldap_err2str() functions
  404. * @param string $sError error message used when ldap error functions
  405. * and connection resource are unavailable
  406. * @return string error message
  407. * @since 1.5.1
  408. */
  409. function ldap_error($sError) {
  410. // it is possible that function_exists() tests are not needed
  411. if(function_exists('ldap_err2str') &&
  412. function_exists('ldap_errno') &&
  413. is_resource($this->linkid)) {
  414. return ldap_err2str(ldap_errno($this->linkid));
  415. // return ldap_error($this->linkid);
  416. } else {
  417. return $sError;
  418. }
  419. }
  420. /* ========================== Public ======================== */
  421. /**
  422. * Search the LDAP server
  423. * @param string $expr search expression
  424. * @return array search results
  425. */
  426. function search($expr) {
  427. /* To be replaced by advanded search expression parsing */
  428. if(is_array($expr)) return false;
  429. // don't allow wide search when listing is disabled.
  430. if ($expr=='*' && ! $this->listing) {
  431. return array();
  432. } elseif ($expr=='*') {
  433. // allow use of wildcard when listing is enabled.
  434. $expression = '(cn=*)';
  435. } else {
  436. /* Convert search from user's charset to the one used in ldap */
  437. $expr = $this->charset_encode($expr);
  438. /* Make sure that search does not contain ldap special chars */
  439. $expression = '(cn=*' . $this->ldapspecialchars($expr) . '*)';
  440. /* Undo sanitizing of * symbol */
  441. $expression = str_replace('\2a','*',$expression);
  442. /* TODO: implement any single character (?) matching */
  443. }
  444. /* Add search filtering */
  445. if ($this->filter!='')
  446. $expression = '(&' . $this->filter . $expression . ')';
  447. /* Use internal search function and return search results */
  448. return $this->ldap_search($expression);
  449. }
  450. /**
  451. * List all entries present in LDAP server
  452. *
  453. * maxrows setting might limit list of returned entries.
  454. * Careful with this -- it could get quite large for big sites.
  455. * @return array all entries in ldap server
  456. */
  457. function list_addr() {
  458. if (! $this->listing)
  459. return array();
  460. /* set wide search expression */
  461. $expression = '(cn=*)';
  462. /* add filtering */
  463. if ($this->filter!='')
  464. $expression = '(&' . $this->filter . $expression .')';
  465. /* use internal search function and return search results */
  466. return $this->ldap_search($expression);
  467. }
  468. }
  469. ?>