abook_ldap_server.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <?php
  2. /**
  3. * abook_ldap_server.php
  4. *
  5. * Address book backend for LDAP server
  6. *
  7. * LDAP filtering code by Tim Bell
  8. * <bhat at users.sourceforge.net> (#539534)
  9. * ADS limit_scope code by Michael Brown
  10. * <mcb30 at users.sourceforge.net> (#1035454)
  11. * StartTLS code by John Lane
  12. * <starfry at users.sourceforge.net> (#1197703)
  13. *
  14. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  15. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  16. * @version $Id$
  17. * @package squirrelmail
  18. * @subpackage addressbook
  19. */
  20. /**
  21. * Address book backend for LDAP server
  22. *
  23. * An array with the following elements must be passed to
  24. * the class constructor (elements marked ? are optional)
  25. *
  26. * Main settings:
  27. * <pre>
  28. * host => LDAP server hostname/IP-address
  29. * base => LDAP server root (base dn). Empty string allowed.
  30. * ? port => LDAP server TCP port number (default: 389)
  31. * ? charset => LDAP server charset (default: utf-8)
  32. * ? name => Name for LDAP server (default "LDAP: hostname")
  33. * Used to tag the result data
  34. * ? maxrows => Maximum # of rows in search result
  35. * ? timeout => Timeout for LDAP operations (in seconds, default: 30)
  36. * Might not work for all LDAP libraries or servers.
  37. * ? binddn => LDAP Bind DN.
  38. * ? bindpw => LDAP Bind Password.
  39. * ? protocol => LDAP Bind protocol.
  40. * </pre>
  41. * Advanced settings:
  42. * <pre>
  43. * ? filter => Filter expression to limit ldap searches
  44. * ? limit_scope => Limits scope to base DN (Specific to Win2k3 ADS).
  45. * ? listing => Controls listing of LDAP directory.
  46. * ? search_tree => Controls subtree or one level search.
  47. * ? starttls => Controls use of StartTLS on LDAP connections
  48. * </pre>
  49. * NOTE. This class should not be used directly. Use the
  50. * "AddressBook" class instead.
  51. * @package squirrelmail
  52. * @subpackage addressbook
  53. */
  54. class abook_ldap_server extends addressbook_backend {
  55. /**
  56. * @var string backend type
  57. */
  58. var $btype = 'remote';
  59. /**
  60. * @var string backend name
  61. */
  62. var $bname = 'ldap_server';
  63. /* Parameters changed by class */
  64. /**
  65. * @var string displayed name
  66. */
  67. var $sname = 'LDAP'; /* Service name */
  68. /**
  69. * @var string LDAP server name or address or url
  70. */
  71. var $server = '';
  72. /**
  73. * @var integer LDAP server port
  74. */
  75. var $port = 389;
  76. /**
  77. * @var string LDAP base DN
  78. */
  79. var $basedn = '';
  80. /**
  81. * @var string charset used for entries in LDAP server
  82. */
  83. var $charset = 'utf-8';
  84. /**
  85. * @var object PHP LDAP link ID
  86. */
  87. var $linkid = false;
  88. /**
  89. * @var bool True if LDAP server is bound
  90. */
  91. var $bound = false;
  92. /**
  93. * @var integer max rows in result
  94. */
  95. var $maxrows = 250;
  96. /**
  97. * @var string ldap filter
  98. * @since 1.5.1
  99. */
  100. var $filter = '';
  101. /**
  102. * @var integer timeout of LDAP operations (in seconds)
  103. */
  104. var $timeout = 30;
  105. /**
  106. * @var string DN to bind to (non-anonymous bind)
  107. * @since 1.5.0 and 1.4.3
  108. */
  109. var $binddn = '';
  110. /**
  111. * @var string password to bind with (non-anonymous bind)
  112. * @since 1.5.0 and 1.4.3
  113. */
  114. var $bindpw = '';
  115. /**
  116. * @var integer protocol used to connect to ldap server
  117. * @since 1.5.0 and 1.4.3
  118. */
  119. var $protocol = '';
  120. /**
  121. * @var boolean limits scope to base dn
  122. * @since 1.5.1
  123. */
  124. var $limit_scope = false;
  125. /**
  126. * @var boolean controls listing of directory
  127. * @since 1.5.1
  128. */
  129. var $listing = false;
  130. /**
  131. * @var boolean controls ldap search type.
  132. * only first level entries are displayed if set to false
  133. * @since 1.5.1
  134. */
  135. var $search_tree = true;
  136. /**
  137. * @var boolean controls use of StartTLS on ldap
  138. * connections. Requires php 4.2+ and protocol >= 3
  139. * @since 1.5.1
  140. */
  141. var $starttls = false;
  142. /**
  143. * Constructor. Connects to database
  144. * @param array connection options
  145. */
  146. function abook_ldap_server($param) {
  147. if(!function_exists('ldap_connect')) {
  148. $this->set_error(_("PHP install does not have LDAP support."));
  149. return;
  150. }
  151. if(is_array($param)) {
  152. $this->server = $param['host'];
  153. $this->basedn = $param['base'];
  154. if(!empty($param['port']))
  155. $this->port = $param['port'];
  156. if(!empty($param['charset']))
  157. $this->charset = strtolower($param['charset']);
  158. if(isset($param['maxrows']))
  159. $this->maxrows = $param['maxrows'];
  160. if(isset($param['timeout']))
  161. $this->timeout = $param['timeout'];
  162. if(isset($param['binddn']))
  163. $this->binddn = $param['binddn'];
  164. if(isset($param['bindpw']))
  165. $this->bindpw = $param['bindpw'];
  166. if(isset($param['protocol']))
  167. $this->protocol = (int) $param['protocol'];
  168. if(isset($param['filter']))
  169. $this->filter = trim($param['filter']);
  170. if(isset($param['limit_scope']))
  171. $this->limit_scope = (bool) $param['limit_scope'];
  172. if(isset($param['listing']))
  173. $this->listing = (bool) $param['listing'];
  174. if(isset($param['search_tree']))
  175. $this->search_tree = (bool) $param['search_tree'];
  176. if(isset($param['starttls']))
  177. $this->starttls = (bool) $param['starttls'];
  178. if(empty($param['name'])) {
  179. $this->sname = 'LDAP: ' . $param['host'];
  180. } else {
  181. $this->sname = $param['name'];
  182. }
  183. /*
  184. * don't open LDAP server on addressbook_init(),
  185. * open ldap connection only on search. Speeds up
  186. * addressbook_init() call.
  187. */
  188. // $this->open(true);
  189. } else {
  190. $this->set_error('Invalid argument to constructor');
  191. }
  192. }
  193. /**
  194. * Open the LDAP server.
  195. * @param bool $new is it a new connection
  196. * @return bool
  197. */
  198. function open($new = false) {
  199. $this->error = '';
  200. /* Connection is already open */
  201. if($this->linkid != false && !$new) {
  202. return true;
  203. }
  204. $this->linkid = @ldap_connect($this->server, $this->port);
  205. /**
  206. * check if connection was successful
  207. * It does not work with OpenLDAP 2.x libraries. Connect error will be
  208. * displayed only on ldap command that tries to make connection
  209. * (ldap_start_tls or ldap_bind).
  210. */
  211. if(!$this->linkid) {
  212. return $this->set_error($this->ldap_error('ldap_connect failed'));
  213. }
  214. if(!empty($this->protocol)) {
  215. // make sure that ldap_set_option() is available before using it
  216. if(! function_exists('ldap_set_option') ||
  217. !@ldap_set_option($this->linkid, LDAP_OPT_PROTOCOL_VERSION, $this->protocol)) {
  218. return $this->set_error('unable to set ldap protocol number');
  219. }
  220. }
  221. /**
  222. * http://www.php.net/ldap-start-tls
  223. * Check if v3 or newer protocol is used,
  224. * check if ldap_start_tls function is available.
  225. * Silently ignore setting, if these requirements are not satisfied.
  226. * Break with error message if somebody tries to start TLS on
  227. * ldaps or socket connection.
  228. */
  229. if($this->starttls &&
  230. !empty($this->protocol) && $this->protocol >= 3 &&
  231. function_exists('ldap_start_tls') ) {
  232. // make sure that $this->server is not ldaps:// or ldapi:// URL.
  233. if (preg_match("/^ldap[si]:\/\/.+/i",$this->server)) {
  234. return $this->set_error("you can't enable starttls on ldaps and ldapi connections.");
  235. }
  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. /**
  357. * calculate length of basedn and remove it from nickname
  358. * ignore whitespaces between RDNs
  359. * Nicknames are shorter and still unique
  360. */
  361. $basedn_len=strlen(preg_replace('/,\s*/',',',trim($this->basedn)));
  362. $nickname=substr(preg_replace('/,\s*/',',',$nickname),0,(-1 - $basedn_len));
  363. $fullname = $this->charset_decode($row['cn'][0]);
  364. if(!empty($row['ou'][0])) {
  365. $label = $this->charset_decode($row['ou'][0]);
  366. }
  367. else if(!empty($row['o'][0])) {
  368. $label = $this->charset_decode($row['o'][0]);
  369. } else {
  370. $label = '';
  371. }
  372. if(empty($row['givenname'][0])) {
  373. $firstname = '';
  374. } else {
  375. $firstname = $this->charset_decode($row['givenname'][0]);
  376. }
  377. if(empty($row['sn'][0])) {
  378. $surname = '';
  379. } else {
  380. $surname = $this->charset_decode($row['sn'][0]);
  381. }
  382. /* Add one row to result for each e-mail address */
  383. if(isset($row['mail']['count'])) {
  384. for($j = 0 ; $j < $row['mail']['count'] ; $j++) {
  385. array_push($ret, array('nickname' => $nickname,
  386. 'name' => $fullname,
  387. 'firstname' => $firstname,
  388. 'lastname' => $surname,
  389. 'email' => $row['mail'][$j],
  390. 'label' => $label,
  391. 'backend' => $this->bnum,
  392. 'source' => &$this->sname));
  393. // Limit number of hits
  394. $returned_rows++;
  395. if(($returned_rows >= $this->maxrows) &&
  396. ($this->maxrows > 0) ) {
  397. ldap_free_result($sret);
  398. return $ret;
  399. }
  400. } // for($j ...)
  401. } // isset($row['mail']['count'])
  402. }
  403. ldap_free_result($sret);
  404. return $ret;
  405. }
  406. /**
  407. * Get error from LDAP resource if possible
  408. *
  409. * Should get error from server using the ldap_errno() and ldap_err2str() functions
  410. * @param string $sError error message used when ldap error functions
  411. * and connection resource are unavailable
  412. * @return string error message
  413. * @since 1.5.1
  414. */
  415. function ldap_error($sError) {
  416. // it is possible that function_exists() tests are not needed
  417. if(function_exists('ldap_err2str') &&
  418. function_exists('ldap_errno') &&
  419. is_resource($this->linkid)) {
  420. return ldap_err2str(ldap_errno($this->linkid));
  421. // return ldap_error($this->linkid);
  422. } else {
  423. return $sError;
  424. }
  425. }
  426. /* ========================== Public ======================== */
  427. /**
  428. * Search the LDAP server
  429. * @param string $expr search expression
  430. * @return array search results
  431. */
  432. function search($expr) {
  433. /* To be replaced by advanded search expression parsing */
  434. if(is_array($expr)) return false;
  435. // don't allow wide search when listing is disabled.
  436. if ($expr=='*' && ! $this->listing) {
  437. return array();
  438. } elseif ($expr=='*') {
  439. // allow use of wildcard when listing is enabled.
  440. $expression = '(cn=*)';
  441. } else {
  442. /* Convert search from user's charset to the one used in ldap */
  443. $expr = $this->charset_encode($expr);
  444. /* sanitize search string */
  445. $expr = $this->ldapspecialchars($expr);
  446. /* Search for same string in cn, main and sn */
  447. $expression = '(|(cn=*'.$expr.'*)(mail=*'.$expr.'*)(sn=*'.$expr.'*))';
  448. /* Undo sanitizing of * symbol */
  449. $expression = str_replace('\2a','*',$expression);
  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. ?>