/** * Find a person by it's (collabPerson)Id * * @param $identifier * @return array[] */ public function findUsersByIdentifier($identifier) { $filter = '(&(objectclass=' . self::LDAP_CLASS_COLLAB_PERSON . ')'; $filter .= '(' . self::LDAP_ATTR_COLLAB_PERSON_ID . '=' . $identifier . '))'; $collection = $this->_ldapClient->search($filter, null, Zend_Ldap::SEARCH_SCOPE_SUB); // Convert the result from a Zend_Ldap object to a plain multi-dimensional array $result = array(); if ($collection !== NULL and $collection !== FALSE) { foreach ($collection as $item) { foreach ($item as $key => $value) { if (is_array($value) && count($value) === 1) { $item[$key] = $value[0]; } } $result[] = $item; } } return $result; }
public function setup() { $path = ''; if ($this->_authType->getAuthType() == 'Ldap') { $path = $this->_authType->getAuthInfo('homedirectory'); } if (!$path) { $ldapOpts = $this->_config->ldap->params; if ($ldapOpts == null) { throw new Exception('LDAP options not configured.', 102); } $ldapOpts = $ldapOpts->toArray(); $ldapOpts['bindRequiresDn'] = true; $ldap = new Zend_Ldap($ldapOpts); $entry = $ldap->search('uid=' . $this->_authType->getUsername())->getFirst(); if (!$entry) { throw new Exception('User ' . $this->_authType->getUsername() . ' LDAP entry not found to create ' . 'their home directory.'); } $path = $entry['homedirectory']; if (!$path) { throw new Exception('User ' . $this->_authType->getUsername() . ' home directory location ' . 'not found.'); } } if (is_array($path)) { $path = $path[0]; } /* Only create the home directory if the path doesn't exist. */ if (is_dir($path)) { return; } /* Run the home directory creation script. */ $script = $this->_config->session->homedirectory->script; if (!$script) { throw new Exception('Home directory creation script not configured.', 108); } if (!is_executable($script)) { throw new Exception('Home directory creation script does not exist or is not executable.', 108); } $args = escapeshellarg($this->_authType->getUsername()) . ' ' . escapeshellarg($path); exec("sudo {$script} {$args}"); }
/** * Populate the given data object * * @param t41_Data_Object $do data object instance * @return boolean */ public function read(t41_Data_Object $do) { $subDn = $this->_mapper ? $this->_mapper->getDatastore($do->getClass()) : null; // get data from backend try { if (!$this->_ressource) { $this->_connect($subDn); } //$data = $this->_ressource->getEntry($do->getUri()->getIdentifier()); $data = $this->_ressource->search('(objectClass=*)', $do->getUri()->getIdentifier()); } catch (Exception $e) { throw new Exception($e->getMessage); } if (empty($data)) { return false; } // Normalize array before mapping // Almost each record in a LDAP result array is an array $data = $this->_flattenArray($data); $do->populate($data, $this->_mapper); return true; }
/** * read ldap / get users and groups from tine an create mapping * * @return array */ protected function _getGroupMapping() { $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Fetching user mapping ...'); $filter = Zend_Ldap_Filter::andFilter(Zend_Ldap_Filter::string($this->_groupBaseFilter)); $mapping = array(); $groupNameMapping = $this->_config->groupNameMapping ? $this->_config->groupNameMapping->toArray() : array(); $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' Group name mapping: ' . print_r($groupNameMapping, TRUE)); $ldapGroups = $this->_ldap->search($filter, $this->_config->ldap->baseDn, $this->_groupSearchScope, array('*', '+')); foreach ($ldapGroups as $group) { $groupname = isset($groupNameMapping[$group['cn'][0]]) ? $groupNameMapping[$group['cn'][0]] : $group['cn'][0]; $ldapUuid = $group['entryuuid'][0]; try { $tineGroup = $this->_tineGroupBackend->getGroupByName($groupname); $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' Group ' . $groupname . ' (' . $group['cn'][0] . '): ' . $tineGroup->getId() . ' -> ' . $ldapUuid); $mapping[$tineGroup->getId()] = $ldapUuid; } catch (Tinebase_Exception_Record_NotDefined $tenf) { // @todo should be: Tinebase_Exception_NotFound $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' Group ' . $groupname . ' (' . $group['cn'][0] . '): ' . $tenf->getMessage()); } } $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' Found ' . count($mapping) . ' groups for the mapping.'); $this->_logger->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($mapping, TRUE)); return $mapping; }
/** * gets userdata from LDAP * * @return array data of currently logged in user */ public static function getUserdata() { // get usernumber from session // if session has not been defined return false $user = new Zend_Session_Namespace('loggedin'); if (isset($user->usernumber) === false) { return false; } $return = array(); $config = new Zend_Config_Ini('../application/configs/config.ini', 'production'); $log_path = $config->ldap->log_path; $multiOptions = $config->ldap->toArray(); $mappingSettings = $config->ldapmappings->toArray(); unset($multiOptions['log_path']); unset($multiOptions['admin_accounts']); $ldap = new Zend_Ldap(); foreach ($multiOptions as $name => $options) { $mappingFirstName = $mappingSettings[$name]['firstName']; $mappingLastName = $mappingSettings[$name]['lastName']; $mappingEMail = $mappingSettings[$name]['EMail']; $permanentId = $mappingSettings[$name]['personId']; $ldap->setOptions($options); try { $ldap->bind(); $ldapsearch = $ldap->search('(uid=' . $user->usernumber . ')', 'dc=tub,dc=tu-harburg,dc=de', Zend_Ldap::SEARCH_SCOPE_ONE); if ($ldapsearch->count() > 0) { $searchresult = $ldapsearch->getFirst(); if (is_array($searchresult[$mappingFirstName]) === true) { $return['firstName'] = $searchresult[$mappingFirstName][0]; } else { $return['firstName'] = $searchresult[$mappingFirstName]; } if (is_array($searchresult[$mappingLastName]) === true) { $return['lastName'] = $searchresult[$mappingLastName][0]; } else { $return['lastName'] = $searchresult[$mappingLastName]; } if (is_array($searchresult[$mappingEMail]) === true) { $return['email'] = $searchresult[$mappingEMail][0]; } else { $return['email'] = $searchresult[$mappingEMail]; } if (is_array($searchresult[$permanentId]) === true) { $return['personId'] = $searchresult[$permanentId][0]; } else { $return['personId'] = $searchresult[$permanentId]; } return $return; } } catch (Zend_Ldap_Exception $zle) { echo ' ' . $zle->getMessage() . "\n"; if ($zle->getCode() === Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) { continue; } } } return $return; }
protected function autenticateLdap() { try { $container = Core_Registry::getContainers(); $ldap = $container['ldap']->getPersist(); $config = \Zend_Registry::get('configs'); $samAccountNameQuery = "samAccountName={$this->getIdentity()}"; /** * Modifica o host para o servidor secundário. */ if ($this->_secondaryHost && isset($config['resources']['container']['ldap']['host']['secondary'])) { $options = $ldap->getOptions(); $options['host'] = $config['resources']['container']['ldap']['host']['secondary']; $ldap = new Zend_Ldap($options); } $admUsr = $config['authenticate']['username']; $admPwd = $config['authenticate']['password']; $ldap->bind($admUsr, $admPwd); $userLdapCount = $ldap->count($samAccountNameQuery); if ($userLdapCount <= 0) { throw new \Sica_Auth_Exception('MN175'); } $userLdap = current($ldap->search($samAccountNameQuery)->toArray()); $pwdLastSetLDAPTimestamp = isset($userLdap['pwdlastset'][0]) ? $userLdap['pwdlastset'][0] : 0; $pwdLastSetLDAPTimestamp_div = bcdiv($pwdLastSetLDAPTimestamp, '10000000'); $pwdLastSetLDAPTimestamp_sub = bcsub($pwdLastSetLDAPTimestamp_div, '11644473600'); $pwdLastSetDate = new \Zend_Date($pwdLastSetLDAPTimestamp_sub, \Zend_Date::TIMESTAMP); $measureTime = new \Zend_Measure_Time(\Zend_Date::now()->sub($pwdLastSetDate)->toValue(), \Zend_Measure_Time::SECOND); $measureTime->convertTo(\Zend_Measure_Time::DAY); $daysLeftToChangePwd = ceil($measureTime->getValue()); if ($daysLeftToChangePwd >= self::LDAP_MAX_PWD_LAST_SET_DAYS) { throw new \Sica_Auth_Exception('EXPIRED_PWD_MSG'); } $ldap->bind($this->getIdentity(), $this->getCredential()); return TRUE; } catch (\Sica_Auth_Exception $authExc) { $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND; $this->_authenticateResultInfo['messages'] = $authExc->getMessage(); return false; } catch (\Zend_Ldap_Exception $ldapExc) { $ldapCode = $ldapExc->getCode(); $message = sprintf('[SICA-e] LDAP Error in %s: "%s"', __METHOD__, $ldapExc->getMessage()); error_log($message); $message = sprintf('[Erro no LDAP] %s', $ldapExc->getMessage()); /** * Se não foi possível contactar o servidor LDAP e se não * for uma tentativa de autenticação no servidor secundário. */ if ($ldapCode == self::LDAP_CONST_CODE_CANT_CONTACT_SERVER && !$this->_secondaryHost) { #Tentativa de autenticação no servidor secundário. $this->_secondaryHost = TRUE; return $this->autenticateLdap(); } if ($ldapCode > 0) { $message = sprintf('LDAP0x%02x', $ldapCode); } if (false !== strpos($ldapExc->getMessage(), self::LDAP_CONST_NT_STATUS_PASSWORD_EXPIRED)) { $message = 'EXPIRED_PWD_MSG'; } $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_UNCATEGORIZED; $this->_authenticateResultInfo['messages'] = $message; return false; } }
private static function _ldapIntegration($userId, $username, $password, $loginServer = null) { $userId = intval($userId); $conf = Phprojekt::getInstance()->getConfig(); $ldapOptions = $conf->authentication->ldap->toArray(); // Zend library does not allow determining from which server the user was found from // That's why we need to request the server from the user during login. $account = null; if ($loginServer !== null && array_key_exists($loginServer, $ldapOptions)) { $searchOpts = $ldapOptions[$loginServer]; try { $ldap = new Zend_Ldap($searchOpts); $ldap->connect(); $ldap->bind($username, $password); $filter = sprintf("(\n &(\n |(objectclass=posixAccount)\n (objectclass=Person)\n )\n (\n |(uid=%s)\n (samAccountName=%s)\n )\n )", $username, $username); $result = $ldap->search($filter, $searchOpts['baseDn']); $account = $result->getFirst(); $ldap->disconnect(); } catch (Exception $e) { throw new Phprojekt_Auth_Exception('Failed to establish a search connection to the LDAP server:' . ' ' . $server . ' ' . 'Please check your configuration for that server.', 8); } } else { throw new Phprojekt_Auth_Exception('Server not specified during login! " . "Please check that your login screen contains the login domain selection.', 9); } if ($account !== null) { // User found $integration = isset($conf->authentication->integration) ? $conf->authentication->integration->toArray() : array(); $firstname = ""; $lastname = ""; $email = ""; if (isset($account['givenname'])) { $firstname = $account['givenname'][0]; } if (isset($account['sn'])) { $lastname = $account['sn'][0]; } if (isset($account['mail'])) { $email = $account['mail'][0]; } // Set user params $params = array(); $params['id'] = intval($userId); // New user has id = 0 $params['username'] = $username; $params['password'] = $password; $admins = array(); if (isset($integration['systemAdmins'])) { $admins = split(",", $integration['systemAdmins']); foreach ($admins as $key => $admin) { $admins[$key] = trim($admin); } } $params['admin'] = in_array($username, $admins) ? 1 : 0; // Default to non-admin (0) if ($userId > 0) { $user = self::_getUser($userId); $params['admin'] = intval($user->admin); } // Integrate with parameters found from LDAP server $params['firstname'] = $firstname; $params['lastname'] = $lastname; $params['email'] = $email; if ($userId > 0) { // Update user parameters with those found from LDAP server $user->find($userId); $params['id'] = $userId; if (!self::_saveUser($params)) { throw new Phprojekt_Auth_Exception('User update failed for LDAP parameters', 10); } } else { // Add new user to PHProjekt // TODO: Default conf could be defined in configuration // Lists needed for checks ? // Set default parameters for users $params['status'] = "A"; // Active user $params['language'] = isset($conf->language) ? $conf->language : "en"; // Conf language / English $params['timeZone'] = "0000"; // (GMT) Greenwich Mean Time: Dublin, Edinburgh, Lisbon, London // Default integration vals from config if (isset($integration['admin']) && $params['admin'] == 0) { $val = intval($integration['admin']); if ($val == 1 || $val == 0) { $params['admin'] = $val; } } if (isset($integration['status'])) { $val = trim(strtoupper($integration['status'])); if (in_array($val, array("A", "I"))) { $params['status'] = $val; } } if (isset($integration['language'])) { $val = trim(strtolower($integration['language'])); $languages = Phprojekt_LanguageAdapter::getLanguageList(); if (array_key_exists($val, $languages)) { $params['language'] = $val; } else { if (($val = array_search('(' . $val . ')', $languages)) !== false) { $params['language'] = $val; } } } if (isset($integration['timeZone'])) { $val = trim(strtolower($integration['timeZone'])); $timezones = Phprojekt_Converter_Time::getTimeZones(); if (array_key_exists($val, $timezones)) { $params['timeZone'] = $val; } else { if (($val = array_search($val, $timezones)) !== false) { $params['timeZone'] = $val; } } } if (!self::_saveUser($params)) { throw new Phprojekt_Auth_Exception('User creation failed after LDAP authentication', 10); } } } else { throw new Phprojekt_Auth_Exception('Failed to find the LDAP user with the given username', 11); } }
/** * DbPatch makes the following variables available to PHP patches: * * @var $this DbPatch_Command_Patch_PHP * @var $writer DbPatch_Core_Writer * @var $db Zend_Db_Adapter_Abstract * @var $phpFile string */ $ldapConfig = EngineBlock_ApplicationSingleton::getInstance()->getConfiguration()->ldap; $ldapOptions = array('host' => $ldapConfig->host, 'useSsl' => $ldapConfig->useSsl, 'username' => $ldapConfig->userName, 'password' => $ldapConfig->password, 'bindRequiresDn' => $ldapConfig->bindRequiresDn, 'accountDomainName' => $ldapConfig->accountDomainName, 'baseDn' => $ldapConfig->baseDn); $ldapClient = new Zend_Ldap($ldapOptions); $ldapClient->bind(); $writer->info("Retrieving all collabPerson entries from LDAP"); //$filter = '(&(objectclass=collabPerson))'; $filter = '(&(objectclass=collabPerson)(!(collabPersonUUID=*)))'; $users = $ldapClient->search($filter); while (count($users) > 0) { $writer->info("Retrieved " . count($users) . " users from LDAP"); foreach ($users as $user) { foreach ($user as $userKey => $userValue) { if (is_array($userValue) && count($userValue) === 1) { $user[$userKey] = $userValue[0]; } } $user['collabpersonuuid'] = (string) Surfnet_Zend_Uuid::generate(); $now = date(DATE_RFC822); $user['collabpersonlastupdated'] = $now; $dn = 'uid=' . $user['uid'] . ',o=' . $user['o'] . ',' . $ldapClient->getBaseDn(); $ldapClient->update($dn, $user); $writer->info("Set UUID '{$user['collabpersonuuid']}' for DN: '{$dn}'"); }