function search_uidspip ($filter,$ldap_server, $ldap_port, $dn) { global $ldap_grp_attr; // LDAP attributs $ldap_grp_attr = array ( "cn", "memberuid" ); $ds = @ldap_connect ( $ldap_server, $ldap_port ); if ( $ds ) { $r = @ldap_bind ( $ds ); // Bind anonyme if ($r) { $result=@ldap_list ($ds, $dn["groups"], $filter, $ldap_grp_attr); if ($result) { $info = ldap_get_entries( $ds, $result ); if ($info["count"]) { // Stockage des logins des membres des classes // dans le tableau $ret $init=0; for ($loop=0; $loop < $info["count"]; $loop++) { $group=split ("[\_\]",$info[$loop]["cn"][0],2); for ( $i = 0; $i < $info[$loop]["memberuid"]["count"]; $i++ ) { $ret[$init]["uid"] = $info[$loop]["memberuid"][$i]; $ret[$init]["cat"] = $group[0]; $init++; } } } ldap_free_result ( $result ); } } @ldap_close ( $ds ); } return $ret; }
/** * Validate group membership * * Searches the LDAP server for group membership of the * supplied username. Quotes all LDAP filter meta characters in * the user name before querying the LDAP server. * * @param string Distinguished Name of the authenticated User * @return boolean */ public function checkGroupMembership($user) { if (!is_resource($this->_resource)) { $this->connect(); } $userDn = $this->_getAccountDn($user); foreach ($this->_options['groups'] as $group) { // make filter $filter = sprintf('(&(%s=%s)(%s=%s)%s)', $this->_options['groupAttr'], $group, $this->_options['memberAttr'], $this->_quoteFilterString($userDn), $this->_options['groupFilter']); // make search base dn $search_basedn = $this->_options['groupDn']; if ($search_basedn != '' && substr($search_basedn, -1) != ',') { $search_basedn .= ','; } $search_basedn .= $this->_options['baseDn']; $func_params = array($this->_resource, $search_basedn, $filter, array($this->_options['memberAttr'])); $func_name = 'ldap_search'; //echo "Searching with $func_name and filter $filter in $search_basedn"; // search if (($result_id = @call_user_func_array($func_name, $func_params)) != false) { if (@ldap_count_entries($this->_resource, $result_id) == 1) { @ldap_free_result($result_id); //echo 'User is member of group'; return true; } } } // default throw new Zend_Ldap_Exception(null, 'User is NOT member of any group!', BDBLdap::LDAP_USER_NOT_MEMBER_OF_GROUP); return false; }
function login($uid, $pwd, $ip = 0) { $this->groups = array(); $this->uid = $uid; if (!($ds = ldap_connect($this->host))) { return false; } if (!($r = @ldap_bind($ds, "uid={$uid},{$this->basedn}", $pwd))) { ldap_unbind($ds); sess_log(LOG_LOGIN, 0, "uid={$uid},{$this->basedn}", 0); return false; } $filter = "(&(objectclass=posixGroup)(memberuid={$uid}))"; $retvals = array("cn"); $sr = ldap_search($ds, $this->basedn, $filter, $retvals); $entries = ldap_get_entries($ds, $sr); $this->groups = array(); for ($i = 0; $i < $entries["count"]; $i++) { for ($j = 0; $j < $entries[$i]["cn"]["count"]; $j++) { $this->groups[] = $entries[$i]["cn"][$j]; } } ldap_free_result($sr); ldap_unbind($ds); // print_r( $this->groups ); sess_log(LOG_LOGIN, 0, "uid={$uid},{$this->basedn}", 1); return true; }
/** * free and close the bound ressources */ function _free() { if (isset($this->_sr) and is_resource($this->_sr)) { ldap_free_result($this->_sr); } if (isset($this->_ldap) and is_resource($this->_ldap)) { ldap_close($this->_ldap); } unset($this->_sr); unset($this->_ldap); }
public function studentid2uid($pStudentId) { if (empty($pStudentId)) { throw new Exception("No parameter given", E_PARAM); } $dn = LDAP_OU . ", " . LDAP_O . ", " . LDAP_C; $filter = "(&(objectclass=" . LDAP_OBJECTCLASS_STUDENT . ")(" . LDAP_ATTRIBUTE_STUDID . "=" . $pStudentId . "))"; $search = ldap_search($this->ldap_conn, $dn, $filter, array("uid")); $entry = ldap_first_entry($this->ldap_conn, $search); $result = @ldap_get_values($this->ldap_conn, $entry, "uid"); ldap_free_result($search); return $result[0]; }
public function __destruct() { $con = $this->connection->getResource(); $this->connection = null; if (null === $this->search || false === $this->search) { return; } $success = ldap_free_result($this->search); $this->search = null; if (!$success) { throw new LdapException(sprintf('Could not free results: %s', ldap_error($con))); } }
function ldapSearchUser($filter, $required) { global $AUTHCFG; $conn = ldapConnectServer(); if ($conn == NULL) { return NULL; } $ident = @ldap_search($conn, $AUTHCFG['ldap_basedn'], $filter, $required); if ($ident) { $result = ldap_get_entries($conn, $ident); ldap_free_result($ident); } ldap_unbind($conn); return $result; }
/** * {@inheritdoc} */ public function execute(LdapOperationInterface $operation) { $allEntries = []; /** @var QueryOperation $operation */ $this->paging()->setIsEnabled($this->shouldUsePaging($operation)); $this->paging()->start($operation->getPageSize(), $operation->getSizeLimit()); do { $this->paging()->next(); $result = @call_user_func($operation->getLdapFunction(), $this->connection->getConnection(), ...$operation->getArguments()); $allEntries = $this->processSearchResult($result, $allEntries); $this->paging()->update($result); } while ($this->paging()->isActive()); $this->paging()->end(); @ldap_free_result($result); return $allEntries; }
public function getValuesFromCas($cas) { $result = ldap_search($this->conn, "ou=People,o=cwru.edu,o=isp", "uid=" . $cas); if ($entries = ldap_first_entry($this->conn, $result)) { $firstName = ldap_get_values($this->conn, $entries, "givenName"); $surname = ldap_get_values($this->conn, $entries, "SN"); $mail = ldap_get_values($this->conn, $entries, "mail"); ldap_free_result($result); $return['firstName'] = $firstName[0]; $return['lastName'] = $surname[0]; $return['mail'] = $mail[0]; return $return; } else { return false; } }
public function search(array $params) { $this->connect(); $ref = array('base_dn' => '', 'filter' => ''); if (count($diff = array_diff_key($ref, $params))) { throw new \Exception(sprintf('You must defined %s', print_r($diff, true))); } $attrs = isset($params['attrs']) ? $params['attrs'] : array(); $this->info(sprintf('ldap_search base_dn %s, filter %s', print_r($params['base_dn'], true), print_r($params['filter'], true))); $search = @ldap_search($this->ress, $params['base_dn'], $params['filter'], $attrs); $this->checkLdapError(); if ($search) { $entries = ldap_get_entries($this->ress, $search); @ldap_free_result($search); return is_array($entries) ? $entries : false; } return false; }
/** * {@inheritdoc} */ public function find($dn, $query, $filter = '*') { if (!is_array($filter)) { $filter = array($filter); } $search = ldap_search($this->connection, $dn, $query, $filter); if (false === $search) { throw new LdapException(ldap_error($this->connection)); } $infos = ldap_get_entries($this->connection, $search); if (false === @ldap_free_result($search)) { throw new LdapException(ldap_error($this->connection)); } if (0 === $infos['count']) { return; } return $infos; }
/** * Generic LDAP search * * @author Alessandro De Zorzi <*****@*****.**> * * @todo add attrsonly, sizelimit, timelimit * * @param string $base_dn * @param string $filter * @param array $attributes * @return array $entries **/ static function phamm_search($base_dn, $filter, $attributes = null, $sort = null) { global $connect; // Do a LDAP search if (isset($attributes)) { $search = ldap_search($connect, $base_dn, $filter, $attributes); } else { $search = ldap_search($connect, $base_dn, $filter); } // Order the results if possible if (version_compare(phpversion(), "4.2.0", ">=")) { ldap_sort($connect, $search, $sort); } // Get entries $entries = ldap_get_entries($connect, $search); // Free the memory ldap_free_result($search); // Return the entry return $entries; }
function ldap_authenticate($user_id, $password) { $ldap_server = LDAP_SERVER; $ldap_port = LDAP_PORT; $ldap_id = LDAP_ID; $ldap_pwd = LDAP_PWD; $ldap_root_dn = LDAP_DN; $ldap_proto = LDAP_PROTOCOL; //$ldap_user = '******' . $user_id . '))'; $ldap_user = '******' . $user_id . ')'; $ldapconn = ldap_connect($ldap_server, $ldap_port); if (!$ldapconn) { error_report_show("login.php", LDAP_CONNECTION_FAILED); } if (!ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, $ldap_proto)) { error_report_show("login.php", LDAP_CONNECTION_FAILED); } $ldapbind = ldap_bind($ldapconn, $ldap_id, $ldap_pwd); if (!$ldapbind) { error_report_show("login.php", INVALID_LOGIN); } $ldapsearch = ldap_search($ldapconn, $ldap_root_dn, $ldap_user); $ldapentries = ldap_get_entries($ldapconn, $ldapsearch); $authenticated = false; if ($ldapentries) { # Try to authenticate to each until we get a match for ($i = 0; $i < $ldapentries['count']; $i++) { $dn = $ldapentries[$i]['dn']; # Attempt to bind with the DN and password if (@ldap_bind($ldapconn, $dn, $password)) { $authenticated = true; break; } } } ldap_close($ldapconn); ldap_free_result($ldapsearch); return $authenticated; }
/** * Retrieve the immediate children DNs of the given $parentDn * * This method is used in recursive methods like {@see delete()} * or {@see copy()} * * @param string|Dn $parentDn * @throws Exception\LdapException * @return array of DNs */ protected function getChildrenDns($parentDn) { if ($parentDn instanceof Dn) { $parentDn = $parentDn->toString(); } $children = array(); ErrorHandler::start(E_WARNING); $search = ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn')); for ($entry = ldap_first_entry($this->getResource(), $search); $entry !== false; $entry = ldap_next_entry($this->getResource(), $entry)) { $childDn = ldap_get_dn($this->getResource(), $entry); if ($childDn === false) { ErrorHandler::stop(); throw new Exception\LdapException($this, 'getting dn'); } $children[] = $childDn; } ldap_free_result($search); ErrorHandler::stop(); return $children; }
/** * Return user info * * Returns info about the given user needs to contain * at least these fields: * * name string full name of the user * mail string email addres of the user * grps array list of groups the user is in * * This LDAP specific function returns the following * addional fields: * * dn string distinguished name (DN) * uid string Posix User ID * inbind bool for internal use - avoid loop in binding * * @author Andreas Gohr <*****@*****.**> * @author Trouble * @author Dan Allen <*****@*****.**> * @author <*****@*****.**> * @author Stephane Chazelas <*****@*****.**> * @return array containing user data or false */ function getUserData($user, $inbind = false) { global $conf; if (!$this->_openLDAP()) { return false; } // force superuser bind if wanted and not bound as superuser yet if ($this->cnf['binddn'] && $this->cnf['bindpw'] && $this->bound < 2) { // use superuser credentials if (!@ldap_bind($this->con, $this->cnf['binddn'], $this->cnf['bindpw'])) { if ($this->cnf['debug']) { msg('LDAP bind as superuser: '******'auth']['pass'], auth_cookiesalt()); $this->checkPass($_SESSION[DOKU_COOKIE]['auth']['user'], $pass); } $info['user'] = $user; $info['server'] = $this->cnf['server']; //get info for given user $base = $this->_makeFilter($this->cnf['usertree'], $info); if (!empty($this->cnf['userfilter'])) { $filter = $this->_makeFilter($this->cnf['userfilter'], $info); } else { $filter = "(ObjectClass=*)"; } $sr = $this->_ldapsearch($this->con, $base, $filter, $this->cnf['userscope']); $result = @ldap_get_entries($this->con, $sr); if ($this->cnf['debug']) { msg('LDAP user search: ' . htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); msg('LDAP search at: ' . htmlspecialchars($base . ' ' . $filter), 0, __LINE__, __FILE__); } // Don't accept more or less than one response if (!is_array($result) || $result['count'] != 1) { return false; //user not found } $user_result = $result[0]; ldap_free_result($sr); // general user info $info['dn'] = $user_result['dn']; $info['gid'] = $user_result['gidnumber'][0]; $info['mail'] = $user_result['mail'][0]; $info['name'] = $user_result['cn'][0]; $info['grps'] = array(); // overwrite if other attribs are specified. if (is_array($this->cnf['mapping'])) { foreach ($this->cnf['mapping'] as $localkey => $key) { if (is_array($key)) { // use regexp to clean up user_result list($key, $regexp) = each($key); if ($user_result[$key]) { foreach ($user_result[$key] as $grp) { if (preg_match($regexp, $grp, $match)) { if ($localkey == 'grps') { $info[$localkey][] = $match[1]; } else { $info[$localkey] = $match[1]; } } } } } else { $info[$localkey] = $user_result[$key][0]; } } } $user_result = array_merge($info, $user_result); //get groups for given user if grouptree is given if ($this->cnf['grouptree'] || $this->cnf['groupfilter']) { $base = $this->_makeFilter($this->cnf['grouptree'], $user_result); $filter = $this->_makeFilter($this->cnf['groupfilter'], $user_result); $sr = $this->_ldapsearch($this->con, $base, $filter, $this->cnf['groupscope'], array($this->cnf['groupkey'])); if ($this->cnf['debug']) { msg('LDAP group search: ' . htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__); msg('LDAP search at: ' . htmlspecialchars($base . ' ' . $filter), 0, __LINE__, __FILE__); } if (!$sr) { msg("LDAP: Reading group memberships failed", -1); return false; } $result = ldap_get_entries($this->con, $sr); ldap_free_result($sr); if (is_array($result)) { foreach ($result as $grp) { if (!empty($grp[$this->cnf['groupkey']][0])) { if ($this->cnf['debug']) { msg('LDAP usergroup: ' . htmlspecialchars($grp[$this->cnf['groupkey']][0]), 0, __LINE__, __FILE__); } $info['grps'][] = $grp[$this->cnf['groupkey']][0]; } } } } // always add the default group to the list of groups if (!in_array($conf['defaultgroup'], $info['grps'])) { $info['grps'][] = $conf['defaultgroup']; } return $info; }
/** * Destructor * * @access protected */ public function _Net_LDAP2_Search() { @ldap_free_result($this->_search); }
public function __destruct() { @ldap_free_result($this->result); }
/** * Frees the resources allocated for this result set. * @return int error code * * @access public */ function free() { $this->_recordset = null; $this->_record = null; ldap_free_result($this->result); $this->result = null; return true; }
function _close() { @ldap_free_result($this->_queryID); $this->_queryID = false; }
/** * Closes the current result set * * @return bool */ public function close() { $isClosed = false; if (is_resource($this->resultId)) { ErrorHandler::start(); $isClosed = ldap_free_result($this->resultId); ErrorHandler::stop(); $this->resultId = null; $this->current = null; } return $isClosed; }
/** * Closes the current result set * * @return bool */ public function close() { $isClosed = false; if (is_resource($this->_resultId)) { $isClosed = @ldap_free_result($this->_resultId); $this->_resultId = null; $this->_current = null; } return $isClosed; }
/** * Validate group membership * * Searches the LDAP server for group membership of the * supplied username. Quotes all LDAP filter meta characters in * the user name before querying the LDAP server. * * @param string Distinguished Name of the authenticated User * @return boolean */ function checkGroup($user) { $this->log('Auth_Container_LDAP::checkGroup() called.', AUTH_LOG_DEBUG); $err = $this->_prepare(); if ($err !== true) { return PEAR::raiseError($err->getMessage(), $err->getCode()); } // make filter $filter = sprintf('(&(%s=%s)(%s=%s)%s)', $this->options['groupattr'], $this->options['group'], $this->options['memberattr'], $this->_quoteFilterString($user), $this->options['groupfilter']); // make search base dn $search_basedn = $this->options['groupdn']; if ($search_basedn != '' && substr($search_basedn, -1) != ',') { $search_basedn .= ','; } $search_basedn .= $this->options['basedn']; $func_params = array($this->conn_id, $search_basedn, $filter, array($this->options['memberattr'])); $func_name = $this->_scope2function($this->options['groupscope']); $this->log("Searching with {$func_name} and filter {$filter} in {$search_basedn}", AUTH_LOG_DEBUG); // search if (($result_id = @call_user_func_array($func_name, $func_params)) != false) { if (@ldap_count_entries($this->conn_id, $result_id) == 1) { @ldap_free_result($result_id); $this->log('User is member of group', AUTH_LOG_DEBUG); return true; } } // default $this->log('User is NOT member of group', AUTH_LOG_DEBUG); return false; }
/** * login * * The script checks provided name and password against remote server. * * This is done by transmitting the user name and the password * to the directory. * * @param string the nickname of the user * @param string the submitted password * @return TRUE on successful authentication, FALSE othewise */ function login($name, $password) { global $context; // we need some parameters if (!isset($this->attributes['authenticator_parameters']) || !$this->attributes['authenticator_parameters']) { Logger::error(i18n::s('Please provide parameters to the authenticator.')); return FALSE; } // tokenize enclosed parameters $tokens = preg_split('/(")/', $this->attributes['authenticator_parameters'], -1, PREG_SPLIT_DELIM_CAPTURE); $outside = TRUE; $parameters = array(); foreach ($tokens as $token) { // sanity check --PREG_SPLIT_NO_EMPTY does not work if (!trim($token)) { // catch "" arguments (used for example as an empty password) if (!$outside) { $parameters[] = ""; } continue; } // begin or end of a token if ($token == '"') { $outside = !$outside; continue; } // outside, each word is a token if ($outside) { $parameters = array_merge($parameters, explode(' ', trim($token))); } else { $parameters[] = trim($token); } } // ensure a minimum number of parameters if (count($parameters) < 1) { Logger::error(i18n::s('Provide at least server name to the LDAP authenticator.')); return FALSE; } // prepare network parameters $server = $parameters[0]; if (strstr($server, ':')) { list($server, $port) = explode(':', $server, 2); } else { $port = 389; } // distinguished name used for bind $bind_dn = ''; if (isset($parameters[1])) { $bind_dn = str_replace('%u', $name, $parameters[1]); } // password used for bind $bind_password = ''; if (isset($parameters[2])) { $bind_password = str_replace('%p', $password, $parameters[2]); } // distinguished name used for search $search_dn = ''; if (isset($parameters[3])) { $search_dn = $parameters[3]; } // encode provided parameters to avoid LDAP injections $name = preg_replace('/([^a-zA-Z0-9\' ])/e', "chr(92).bin2hex('\$1')", $name); $password = preg_replace('/([^a-zA-Z0-9\' ])/e', "chr(92).bin2hex('\$1')", $password); // search expression $search_filter = ''; if (isset($parameters[4])) { $search_filter = str_replace(array('%u', '%p'), array($name, $password), $parameters[4]); } // parse options $opt_deref = LDAP_DEREF_NEVER; $opt_protocol_version = 3; $opt_sizelimit = 0; $opt_timelimit = 0; $opt_ldap_search_func = "ldap_search"; if (isset($parameters[5])) { $tokens = preg_split('/,/', $parameters[5], -1, PREG_SPLIT_NO_EMPTY); foreach ($tokens as $token) { $argerror = $valerror = 0; $argerror_s = $argerror_c = ''; list($key, $val) = explode('=', $token, 2); if (!strcasecmp($key, "DEREF")) { if (!strcasecmp($val, "never")) { $opt_deref = LDAP_DEREF_NEVER; } elseif (!strcasecmp($val, "always")) { $opt_deref = LDAP_DEREF_ALWAYS; } else { $valerror = 1; } } elseif (!strcasecmp($key, "PROTOCOL_VERSION")) { if ($val == 2 || $val == 3) { $opt_protocol_version = $val; } else { $valerror = 1; } } elseif (!strcasecmp($key, "SCOPE")) { if (!strcasecmp($val, "one")) { $opt_ldap_search_func = "ldap_list"; } elseif (!strcasecmp($val, "sub")) { $opt_ldap_search_func = "ldap_search"; } else { $valerror = 1; } } elseif (!strcasecmp($key, "SIZELIMIT")) { if (ctype_digit($val)) { $opt_sizelimit = $val; } else { $valerror = 1; } } elseif (!strcasecmp($key, "TIMELIMIT")) { if (ctype_digit($val)) { $opt_timelimit = $val; } else { $valerror = 1; } } else { $argerror_s = sprintf(i18n::s("Unknown LDAP option %s."), $key); $argerror_c = sprintf(i18n::c("Unknown LDAP option %s."), $key); $argerror = 1; } // a wrong value must trigger an error message if ($valerror) { $argerror_s = sprintf(i18n::s("LDAP %s: bad value '%s'."), $key, $val); $argerror_c = sprintf(i18n::c("LDAP %s: bad value '%s'."), $key, $val); $argerror = 1; } // print any error message raised while parsing the option if ($argerror) { Logger::error($argerror_s); if ($context['with_debug'] == 'Y') { Logger::remember('users/authenticators/ldap.php: ' . $argerror_c, '', 'debug'); } return FALSE; } } } // ensure we can move forward if (!is_callable('ldap_connect')) { Logger::error(i18n::s('Please activate the LDAP library.')); if ($context['with_debug'] == 'Y') { Logger::remember('users/authenticators/ldap.php: ' . i18n::c('Please activate the LDAP library.'), '', 'debug'); } return FALSE; } // open network socket if (!($handle = @ldap_connect($server, $port))) { Logger::error(sprintf(i18n::s('Impossible to connect to %.'), $server)); if ($context['with_debug'] == 'Y') { Logger::remember('users/authenticators/ldap.php: ' . sprintf(i18n::c('Impossible to connect to %.'), $server . ':' . $port), '', 'debug'); } return FALSE; } // set desired options @ldap_set_option($handle, LDAP_OPT_PROTOCOL_VERSION, $opt_protocol_version); @ldap_set_option($handle, LDAP_OPT_DEREF, $opt_deref); @ldap_set_option($handle, LDAP_OPT_SIZELIMIT, $opt_sizelimit); @ldap_set_option($handle, LDAP_OPT_TIMELIMIT, $opt_timelimit); // bind to directory, namely or anonymously if ($bind_dn && @ldap_bind($handle, $bind_dn, $bind_password)) { } elseif (!$bind_dn && @ldap_bind($handle)) { } else { Logger::error(sprintf(i18n::s('Impossible to bind to LDAP server %s.'), $server) . BR . ldap_errno($handle) . ': ' . ldap_error($handle)); if ($context['with_debug'] == 'Y') { Logger::remember('users/authenticators/ldap.php: ' . sprintf(i18n::c('Impossible to bind to LDAP server %s.'), $server . ' ' . $bind_dn . ' ' . $bind_password), ldap_errno($handle) . ': ' . ldap_error($handle), 'debug'); } ldap_close($handle); return FALSE; } // stop on successful bind if (!trim($search_filter)) { ldap_close($handle); return TRUE; } // search the directory if (!($result = @call_user_func($opt_ldap_search_func, $handle, $search_dn, $search_filter, array('cn')))) { Logger::error(sprintf(i18n::s('Impossible to search in LDAP server %s.'), $server) . BR . ldap_errno($handle) . ': ' . ldap_error($handle)); if ($context['with_debug'] == 'Y') { Logger::remember('users/authenticators/ldap.php: ' . sprintf(i18n::c('Impossible to search in LDAP server %s.'), $server), ldap_errno($handle) . ': ' . ldap_error($handle), 'debug'); } ldap_close($handle); return FALSE; } // successful match if (@ldap_first_entry($handle, $result) !== FALSE) { ldap_free_result($result); ldap_close($handle); return TRUE; } // authentication has failed if ($context['with_debug'] == 'Y') { Logger::remember('users/authenticators/ldap.php: ' . sprintf(i18n::c('No match for %s.'), $search_filter), '', 'debug'); } ldap_free_result($result); ldap_close($handle); return FALSE; }
/** * @param array $attrs An array of names of desired attributes * @return array An array of the attributes representing the account * @throws Zend_Ldap_Exception */ private function _getAccount($acctname, $attrs = null) { $baseDn = $this->_getBaseDn(); if (!$baseDn) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, 'Base DN not set'); } $accountFilter = $this->_getAccountFilter($acctname); if (!$accountFilter) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, 'Invalid account filter'); } if (!is_resource($this->_resource)) $this->bind(); $resource = $this->_resource; $str = $accountFilter; $code = 0; /** * @todo break out search operation into simple function (private for now) */ if (!extension_loaded('ldap')) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception(null, 'LDAP extension not loaded'); } $result = @ldap_search($resource, $baseDn, $accountFilter, $attrs); if (is_resource($result) === true) { $count = @ldap_count_entries($resource, $result); if ($count == 1) { $entry = @ldap_first_entry($resource, $result); if ($entry) { $acct = array('dn' => @ldap_get_dn($resource, $entry)); $name = @ldap_first_attribute($resource, $entry, $berptr); while ($name) { $data = @ldap_get_values_len($resource, $entry, $name); $acct[$name] = $data; $name = @ldap_next_attribute($resource, $entry, $berptr); } @ldap_free_result($result); return $acct; } } else if ($count == 0) { /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; $code = Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT; } else { /** * @todo limit search to 1 record and remove some of this logic? */ $resource = null; $str = "$accountFilter: Unexpected result count: $count"; /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; $code = Zend_Ldap_Exception::LDAP_OPERATIONS_ERROR; } @ldap_free_result($result); } /** * @see Zend_Ldap_Exception */ require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception($resource, $str, $code); }
protected function recursive_delete($connection, $dn, $filter) { if ($res = ldap_list($connection, $dn, $filter, array('dn'))) { $info = ldap_get_entries($connection, $res); ldap_free_result($res); if ($info['count'] > 0) { if ($res = ldap_search($connection, "{$filter},{$dn}", 'cn=*', array('dn'))) { $info = ldap_get_entries($connection, $res); ldap_free_result($res); foreach ($info as $i) { if (isset($i['dn'])) { ldap_delete($connection, $i['dn']); } } } if ($res = ldap_search($connection, "{$filter},{$dn}", 'ou=*', array('dn'))) { $info = ldap_get_entries($connection, $res); ldap_free_result($res); foreach ($info as $i) { if (isset($i['dn']) and $info[0]['dn'] != $i['dn']) { ldap_delete($connection, $i['dn']); } } } ldap_delete($connection, "{$filter},{$dn}"); } } }
private function getUserData($user) { if (!$this->connect()) { return false; } // force superuser bind if wanted and not bound as superuser yet if (!empty($this->cnf['bind_dn']) && !empty($this->cnf['bind_password']) && $this->bound < 2) { if (!ldap_bind($this->ds, $this->cnf['bind_dn'], $this->cnf['bind_password'])) { return false; } $this->bound = 2; } // with no superuser creds we continue as user or anonymous here $info['user'] = $user; $info['host'] = $this->cnf['host']; // get info for given user $base = $this->makeFilter($this->cnf['base_dn'], $info); if (isset($this->cnf['userfilter']) && !empty($this->cnf['userfilter'])) { $filter = $this->makeFilter($this->cnf['userfilter'], $info); } else { $filter = '(ObjectClass=*)'; } $sr = ldap_search($this->ds, $base, $filter); $result = ldap_get_entries($this->ds, $sr); // don't accept more or less than one response if ($result['count'] != 1) { error('LDAP: User not found.'); return false; } $user_result = $result[0]; ldap_free_result($sr); // general user info $info['dn'] = $user_result['dn']; $info['name'] = $user_result['cn'][0]; $info['grps'] = array(); // overwrite if other attribs are specified. if (is_array($this->cnf['mapping'])) { foreach ($this->cnf['mapping'] as $localkey => $key) { $info[$localkey] = isset($user_result[$key]) ? $user_result[$key][0] : null; } } $user_result = zbx_array_merge($info, $user_result); // get groups for given user if grouptree is given if (isset($this->cnf['grouptree']) && isset($this->cnf['groupfilter'])) { $base = $this->makeFilter($this->cnf['grouptree'], $user_result); $filter = $this->makeFilter($this->cnf['groupfilter'], $user_result); $sr = ldap_search($this->ds, $base, $filter, array($this->cnf['groupkey'])); if (!$sr) { error('LDAP: Reading group memberships failed.'); return false; } $result = ldap_get_entries($this->ds, $sr); foreach ($result as $grp) { if (!empty($grp[$this->cnf['groupkey']][0])) { $info['grps'][] = $grp[$this->cnf['groupkey']][0]; } } } // always add the default group to the list of groups if (isset($conf['defaultgroup']) && !str_in_array($conf['defaultgroup'], $info['grps'])) { $info['grps'][] = $conf['defaultgroup']; } return $info; }
/** * Retrieve current user's scripts. * * @param resource $ldapcn The connection to the LDAP server. * @param string $userDN Set to the user object's real DN. * * @return array Script sources list. * @throws Ingo_Exception */ protected function _getScripts($ldapcn, &$userDN) { $attrs = array($this->_params['script_attribute'], 'dn'); $filter = $this->_substUser($this->_params['script_filter']); /* Find the user object. */ $sr = @ldap_search($ldapcn, $this->_params['script_base'], $filter, $attrs); if ($sr === false) { throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } if (@ldap_count_entries($ldapcn, $sr) != 1) { throw new Ingo_Exception(sprintf(_("Expected 1 object, got %d."), ldap_count_entries($ldapcn, $sr))); } $ent = @ldap_first_entry($ldapcn, $sr); if ($ent === false) { throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } /* Retrieve the user's DN. */ $v = @ldap_get_dn($ldapcn, $ent); if ($v === false) { @ldap_free_result($sr); throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } $userDN = $v; /* Retrieve the user's scripts. */ $attrs = @ldap_get_attributes($ldapcn, $ent); @ldap_free_result($sr); if ($attrs === false) { throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } /* Attribute can be in any case, and can have a ";binary" * specifier. */ $regexp = '/^' . preg_quote($this->_params['script_attribute'], '/') . '(?:;.*)?$/i'; unset($attrs['count']); foreach ($attrs as $name => $values) { if (preg_match($regexp, $name)) { unset($values['count']); return array_values($values); } } return array(); }
/** * LDAP authetication to login * * @param integer $p_user_id UserID * @param string $p_password Password * * @return user */ function ldapAuthenticate($p_user_id, $p_password) { $g_enable_ssl_connectivity = ENABLE_SSL_CONNECTIVITY; $g_ldap_protocol_version = LDAP_PROTOCOL_VERSION; $g_ldap_server = LDAP_SERVER; $g_ldap_port = LDAP_PORT; $g_ldap_root_dn = LDAP_ROOT_DN; $g_ldap_organisation = ''; $g_ldap_uid_field = LDAP_UID_FIELD; $g_ldap_bind_dn = LDAP_BIND_DN; // A system account to login to LDAP $g_ldap_bind_passwd = LDAP_BIND_PASSWD; // System account password // if password is empty and ldap allows anonymous login, then // the user will be able to login, hence, we need to check // for this special case. if (empty($p_password)) { return false; } $t_ldap_organization = $g_ldap_organisation; $t_ldap_root_dn = $g_ldap_root_dn; $t_username = $p_user_id; $t_ldap_uid_field = $g_ldap_uid_field; $t_search_filter = "(&{$t_ldap_organization}({$t_ldap_uid_field}={$t_username}))"; $t_search_attrs = array($t_ldap_uid_field, 'name', 'mail'); $t_ldap_server = $g_enable_ssl_connectivity == 'true' ? 'ldaps://' . $g_ldap_server : 'ldap://' . $g_ldap_server; $t_ldap_port = $g_ldap_port; $t_ds = @ldap_connect($t_ldap_server, $t_ldap_port); if ($t_ds > 0) { $t_protocol_version = $g_ldap_protocol_version; if ($t_protocol_version > 0) { ldap_set_option($t_ds, LDAP_OPT_PROTOCOL_VERSION, $t_protocol_version); ldap_set_option($t_ds, LDAP_OPT_REFERRALS, 0); } // If no Bind DN and Password is set, attempt to login as the configured // Bind DN. $t_password = ''; $t_binddn = ''; if (empty($t_binddn) && empty($t_password)) { $t_binddn = $g_ldap_bind_dn; $t_password = $g_ldap_bind_passwd; } if (!empty($t_binddn) && !empty($t_password)) { $t_br = @ldap_bind($t_ds, $t_binddn, $t_password); } else { // Either the Bind DN or the Password are empty, so attempt an anonymous bind. $t_br = @ldap_bind($t_ds); } if (!$t_br) { return 'ERROR_LDAP_AUTH_FAILED'; } } else { return 'ERROR_LDAP_SERVER_CONNECT_FAILED'; } // Search for the user id $t_sr = ldap_search($t_ds, $t_ldap_root_dn, $t_search_filter, $t_search_attrs); $t_info = ldap_get_entries($t_ds, $t_sr); $user['User']['is_username_exits'] = false; $user['User']['is_password_matched'] = false; if ($t_info) { $user['User']['is_username_exits'] = true; // Try to authenticate to each until we get a match for ($i = 0; $i < $t_info['count']; $i++) { $t_dn = $t_info[$i]['dn']; // Attempt to bind with the DN and password if ($_data1 = @ldap_bind($t_ds, $t_dn, $p_password)) { $user['User']['is_password_matched'] = true; if (isset($t_info[$i]['name'])) { $user['User']['first_name'] = $t_info[$i]['name'][0]; } if (isset($t_info[$i]['mail'])) { $user['User']['email'] = $t_info[$i]['mail'][0]; } break; // Don't need to go any further } } } if (empty($user['User']['email'])) { return 'ERROR_LDAP_EMAIL_NOT_ASSOCIATED'; } ldap_free_result($t_sr); ldap_unbind($t_ds); return $user; }
/** * Retrieve the immediate children DNs of the given $parentDn * * This method is used in recursive methods like {@see delete()} * or {@see copy()} * * @param string|Zend_Ldap_Dn $parentDn * @return array of DNs */ protected function _getChildrenDns($parentDn) { if ($parentDn instanceof Zend_Ldap_Dn) { $parentDn = $parentDn->toString(); } $children = array(); $search = @ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn')); for ($entry = @ldap_first_entry($this->getResource(), $search); $entry !== false; $entry = @ldap_next_entry($this->getResource(), $entry)) { $childDn = @ldap_get_dn($this->getResource(), $entry); if ($childDn === false) { /** * @see Zend_Ldap_Exception */ #require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception($this, 'getting dn'); } $children[] = $childDn; } @ldap_free_result($search); return $children; }
/** * Load all attribute of a LDAP user * * @param User $user User to search for. Not used if a filter is provided. * @param string $filter Filter for search. Must start with &. * Examples: &(objectClass=inetOrgPerson) &(objectClass=user)(objectCategory=person) &(isMemberOf=cn=Sales,ou=Groups,dc=opencsi,dc=com) * @return int >0 if OK, <0 if KO */ function fetch($user, $filter) { // Perform the search and get the entry handles // if the directory is AD, then bind first with the search user first if ($this->serverType == "activedirectory") { $this->bindauth($this->searchUser, $this->searchPassword); } $searchDN = $this->people; // TODO Why searching in people then domain ? $result = ''; $i = 0; while ($i <= 2) { dol_syslog(get_class($this) . "::fetch search with searchDN=" . $searchDN . " filter=" . $filter); $this->result = @ldap_search($this->connection, $searchDN, $filter); if ($this->result) { $result = @ldap_get_entries($this->connection, $this->result); if ($result['count'] > 0) { dol_syslog('Ldap::fetch search found ' . $result['count'] . ' records'); } else { dol_syslog('Ldap::fetch search returns but found no records'); } //var_dump($result);exit; } else { $this->error = ldap_errno($this->connection) . " " . ldap_error($this->connection); dol_syslog(get_class($this) . "::fetch search fails"); return -1; } if (!$result) { // Si pas de resultat on cherche dans le domaine $searchDN = $this->domain; $i++; } else { break; } } if (!$result) { $this->error = ldap_errno($this->connection) . " " . ldap_error($this->connection); return -1; } else { $this->name = $this->convToOutputCharset($result[0][$this->attr_name][0], $this->ldapcharset); $this->firstname = $this->convToOutputCharset($result[0][$this->attr_firstname][0], $this->ldapcharset); $this->login = $this->convToOutputCharset($result[0][$this->attr_login][0], $this->ldapcharset); $this->phone = $this->convToOutputCharset($result[0][$this->attr_phone][0], $this->ldapcharset); $this->skype = $this->convToOutputCharset($result[0][$this->attr_skype][0], $this->ldapcharset); $this->fax = $this->convToOutputCharset($result[0][$this->attr_fax][0], $this->ldapcharset); $this->mail = $this->convToOutputCharset($result[0][$this->attr_mail][0], $this->ldapcharset); $this->mobile = $this->convToOutputCharset($result[0][$this->attr_mobile][0], $this->ldapcharset); $this->uacf = $this->parseUACF($this->convToOutputCharset($result[0]["useraccountcontrol"][0], $this->ldapcharset)); if (isset($result[0]["pwdlastset"][0])) { $this->pwdlastset = $result[0]["pwdlastset"][0] != 0 ? $this->convert_time($this->convToOutputCharset($result[0]["pwdlastset"][0], $this->ldapcharset)) : 0; } else { $this->pwdlastset = -1; } if (!$this->name && !$this->login) { $this->pwdlastset = -1; } $this->badpwdtime = $this->convert_time($this->convToOutputCharset($result[0]["badpasswordtime"][0], $this->ldapcharset)); // FQDN domain $domain = str_replace('dc=', '', $this->domain); $domain = str_replace(',', '.', $domain); $this->domainFQDN = $domain; // Set ldapUserDn (each user can have a different dn) //var_dump($result[0]);exit; $this->ldapUserDN = $result[0]['dn']; ldap_free_result($this->result); return 1; } }