abook_ldap_server.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 these requirements are not satisfied.
  227. * Break with error message if somebody tries to start TLS on
  228. * ldaps or socket connection.
  229. */
  230. if($this->starttls &&
  231. !empty($this->protocol) && $this->protocol >= 3 &&
  232. function_exists('ldap_start_tls') ) {
  233. // make sure that $this->server is not ldaps:// or ldapi:// URL.
  234. if (preg_match("/^ldap[si]:\/\/.+/i",$this->server)) {
  235. return $this->set_error("you can't enable starttls on ldaps and ldapi connections.");
  236. }
  237. // try starting tls
  238. if (! @ldap_start_tls($this->linkid)) {
  239. // set error if call fails
  240. return $this->set_error($this->ldap_error('ldap_start_tls failed'));
  241. }
  242. }
  243. if(!empty($this->limit_scope) && $this->limit_scope) {
  244. if(empty($this->protocol) || intval($this->protocol) < 3) {
  245. return $this->set_error('limit_scope requires protocol >= 3');
  246. }
  247. // See http://msdn.microsoft.com/library/en-us/ldap/ldap/ldap_server_domain_scope_oid.asp
  248. $ctrl = array ( "oid" => "1.2.840.113556.1.4.1339", "iscritical" => TRUE );
  249. /*
  250. * Option is set only during connection.
  251. * It does not cause immediate errors with OpenLDAP 2.x libraries.
  252. */
  253. if(! function_exists('ldap_set_option') ||
  254. !@ldap_set_option($this->linkid, LDAP_OPT_SERVER_CONTROLS, array($ctrl))) {
  255. return $this->set_error($this->ldap_error('limit domain scope failed'));
  256. }
  257. }
  258. // authenticated bind
  259. if(!empty($this->binddn)) {
  260. if(!@ldap_bind($this->linkid, $this->binddn, $this->bindpw)) {
  261. return $this->set_error($this->ldap_error('authenticated ldap_bind failed'));
  262. }
  263. } else {
  264. // anonymous bind
  265. if(!@ldap_bind($this->linkid)) {
  266. return $this->set_error($this->ldap_error('anonymous ldap_bind failed'));
  267. }
  268. }
  269. $this->bound = true;
  270. return true;
  271. }
  272. /**
  273. * Encode string to the charset used by this LDAP server
  274. * @param string string that has to be encoded
  275. * @return string encoded string
  276. */
  277. function charset_encode($str) {
  278. global $default_charset;
  279. if($this->charset != $default_charset) {
  280. return charset_convert($default_charset,$str,$this->charset,false);
  281. } else {
  282. return $str;
  283. }
  284. }
  285. /**
  286. * Decode from charset used by this LDAP server to charset used by translation
  287. *
  288. * Uses SquirrelMail charset_decode functions
  289. * @param string string that has to be decoded
  290. * @return string decoded string
  291. */
  292. function charset_decode($str) {
  293. global $default_charset;
  294. if ($this->charset != $default_charset) {
  295. return charset_convert($this->charset,$str,$default_charset,false);
  296. } else {
  297. return $str;
  298. }
  299. }
  300. /**
  301. * Sanitizes ldap search strings.
  302. * See rfc2254
  303. * @link http://www.faqs.org/rfcs/rfc2254.html
  304. * @since 1.5.1 and 1.4.5
  305. * @param string $string
  306. * @return string sanitized string
  307. */
  308. function ldapspecialchars($string) {
  309. $sanitized=array('\\' => '\5c',
  310. '*' => '\2a',
  311. '(' => '\28',
  312. ')' => '\29',
  313. "\x00" => '\00');
  314. return str_replace(array_keys($sanitized),array_values($sanitized),$string);
  315. }
  316. /**
  317. * Search LDAP server.
  318. *
  319. * Warning: You must make sure that ldap query is correctly formated and
  320. * sanitize use of special ldap keywords.
  321. * @param string $expression ldap query
  322. * @return array search results (false on error)
  323. * @since 1.5.1
  324. */
  325. function ldap_search($expression) {
  326. /* Make sure connection is there */
  327. if(!$this->open()) {
  328. return false;
  329. }
  330. if ($this->search_tree) {
  331. // ldap_search - search subtree
  332. $sret = @ldap_search($this->linkid, $this->basedn, $expression,
  333. array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
  334. 0, $this->maxrows, $this->timeout);
  335. } else {
  336. // ldap_list - search one level
  337. $sret = @ldap_list($this->linkid, $this->basedn, $expression,
  338. array('dn', 'o', 'ou', 'sn', 'givenname', 'cn', 'mail'),
  339. 0, $this->maxrows, $this->timeout);
  340. }
  341. /* Return error if search failed */
  342. if(!$sret) {
  343. return $this->set_error($this->ldap_error('ldap_search failed'));
  344. }
  345. if(@ldap_count_entries($this->linkid, $sret) <= 0) {
  346. return array();
  347. }
  348. /* Get results */
  349. $ret = array();
  350. $returned_rows = 0;
  351. $res = @ldap_get_entries($this->linkid, $sret);
  352. for($i = 0 ; $i < $res['count'] ; $i++) {
  353. $row = $res[$i];
  354. /* Extract data common for all e-mail addresses
  355. * of an object. Use only the first name */
  356. $nickname = $this->charset_decode($row['dn']);
  357. /**
  358. * calculate length of basedn and remove it from nickname
  359. * ignore whitespaces between RDNs
  360. * Nicknames are shorter and still unique
  361. */
  362. $basedn_len=strlen(preg_replace('/,\s*/',',',trim($this->basedn)));
  363. $nickname=substr(preg_replace('/,\s*/',',',$nickname),0,(-1 - $basedn_len));
  364. $fullname = $this->charset_decode($row['cn'][0]);
  365. if(!empty($row['ou'][0])) {
  366. $label = $this->charset_decode($row['ou'][0]);
  367. }
  368. else if(!empty($row['o'][0])) {
  369. $label = $this->charset_decode($row['o'][0]);
  370. } else {
  371. $label = '';
  372. }
  373. if(empty($row['givenname'][0])) {
  374. $firstname = '';
  375. } else {
  376. $firstname = $this->charset_decode($row['givenname'][0]);
  377. }
  378. if(empty($row['sn'][0])) {
  379. $surname = '';
  380. } else {
  381. $surname = $this->charset_decode($row['sn'][0]);
  382. }
  383. /* Add one row to result for each e-mail address */
  384. if(isset($row['mail']['count'])) {
  385. for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
  386. array_push($ret, array('nickname' => $nickname,
  387. 'name' => $fullname,
  388. 'firstname' => $firstname,
  389. 'lastname' => $surname,
  390. 'email' => $row['mail'][$j],
  391. 'label' => $label,
  392. 'backend' => $this->bnum,
  393. 'source' => &$this->sname));
  394. // Limit number of hits
  395. $returned_rows++;
  396. if(($returned_rows >= $this->maxrows) &&
  397. ($this->maxrows > 0) ) {
  398. ldap_free_result($sret);
  399. return $ret;
  400. }
  401. } // for($j ...)
  402. } // isset($row['mail']['count'])
  403. }
  404. ldap_free_result($sret);
  405. return $ret;
  406. }
  407. /**
  408. * Get error from LDAP resource if possible
  409. *
  410. * Should get error from server using the ldap_errno() and ldap_err2str() functions
  411. * @param string $sError error message used when ldap error functions
  412. * and connection resource are unavailable
  413. * @return string error message
  414. * @since 1.5.1
  415. */
  416. function ldap_error($sError) {
  417. // it is possible that function_exists() tests are not needed
  418. if(function_exists('ldap_err2str') &&
  419. function_exists('ldap_errno') &&
  420. is_resource($this->linkid)) {
  421. return ldap_err2str(ldap_errno($this->linkid));
  422. // return ldap_error($this->linkid);
  423. } else {
  424. return $sError;
  425. }
  426. }
  427. /* ========================== Public ======================== */
  428. /**
  429. * Search the LDAP server
  430. * @param string $expr search expression
  431. * @return array search results
  432. */
  433. function search($expr) {
  434. /* To be replaced by advanded search expression parsing */
  435. if(is_array($expr)) return false;
  436. // don't allow wide search when listing is disabled.
  437. if ($expr=='*' && ! $this->listing) {
  438. return array();
  439. } elseif ($expr=='*') {
  440. // allow use of wildcard when listing is enabled.
  441. $expression = '(cn=*)';
  442. } else {
  443. /* Convert search from user's charset to the one used in ldap */
  444. $expr = $this->charset_encode($expr);
  445. /* Make sure that search does not contain ldap special chars */
  446. $expression = '(cn=*' . $this->ldapspecialchars($expr) . '*)';
  447. /* Undo sanitizing of * symbol */
  448. $expression = str_replace('\2a','*',$expression);
  449. /* TODO: implement any single character (?) matching */
  450. }
  451. /* Add search filtering */
  452. if ($this->filter!='')
  453. $expression = '(&' . $this->filter . $expression . ')';
  454. /* Use internal search function and return search results */
  455. return $this->ldap_search($expression);
  456. }
  457. /**
  458. * List all entries present in LDAP server
  459. *
  460. * maxrows setting might limit list of returned entries.
  461. * Careful with this -- it could get quite large for big sites.
  462. * @return array all entries in ldap server
  463. */
  464. function list_addr() {
  465. if (! $this->listing)
  466. return array();
  467. /* set wide search expression */
  468. $expression = '(cn=*)';
  469. /* add filtering */
  470. if ($this->filter!='')
  471. $expression = '(&' . $this->filter . $expression .')';
  472. /* use internal search function and return search results */
  473. return $this->ldap_search($expression);
  474. }
  475. }
  476. ?>