protected function setUp() { if (!TESTS_ZEND_LDAP_ONLINE_ENABLED) { $this->markTestSkipped("Test skipped due to test configuration"); return; } $options = array('host' => TESTS_ZEND_LDAP_HOST, 'username' => TESTS_ZEND_LDAP_USERNAME, 'password' => TESTS_ZEND_LDAP_PASSWORD, 'baseDn' => TESTS_ZEND_LDAP_WRITEABLE_SUBTREE); if (defined('TESTS_ZEND_LDAP_PORT') && TESTS_ZEND_LDAP_PORT != 389) { $options['port'] = TESTS_ZEND_LDAP_PORT; } if (defined('TESTS_ZEND_LDAP_USE_START_TLS')) { $options['useStartTls'] = TESTS_ZEND_LDAP_USE_START_TLS; } if (defined('TESTS_ZEND_LDAP_USE_SSL')) { $options['useSsl'] = TESTS_ZEND_LDAP_USE_SSL; } if (defined('TESTS_ZEND_LDAP_BIND_REQUIRES_DN')) { $options['bindRequiresDn'] = TESTS_ZEND_LDAP_BIND_REQUIRES_DN; } if (defined('TESTS_ZEND_LDAP_ACCOUNT_FILTER_FORMAT')) { $options['accountFilterFormat'] = TESTS_ZEND_LDAP_ACCOUNT_FILTER_FORMAT; } if (defined('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME')) { $options['accountDomainName'] = TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME; } if (defined('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME_SHORT')) { $options['accountDomainNameShort'] = TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME_SHORT; } $this->_ldap = new Zend_Ldap($options); $this->_ldap->bind(); }
public function isValid($value) { $request = Zend_Controller_Front::getInstance()->getRequest(); $fields = $request->getParams(); $config = Zend_Registry::get('config'); $servers = $config['ldap']; $valid = false; foreach ($servers as $server) { try { $ldap = new Zend_Ldap($server); $ldap->bind($fields['ldapUser'], $fields['ldapPassword']); $ldapEntry = $ldap->searchEntries(Zend_Ldap_Filter::equals('samaccountname', $value)); if (!empty($ldapEntry)) { $valid |= true; } } catch (Exception $e) { $valid |= false; } } if (!$valid) { $this->_error(self::NOT_EXISTS); return false; } return true; }
public function checkDomain($params) { foreach ($params as $param) { $data[$param['name']] = $param['value']; } if (empty($data['toCheck'])) { throw new Exception('Podaj login zgłaszającego!'); } $logic = new Logic_Validate_LdapLogin(); $config = Zend_Registry::get('config'); $servers = $config['ldap']; foreach ($servers as $server) { $ldap = new Zend_Ldap($server); $ldap->bind($data['login'], $data['password']); $ldapEntry = $ldap->searchEntries(Zend_Ldap_Filter::equals('samaccountname', $data['toCheck'])); if (!empty($ldapEntry)) { break; } } if (!empty($ldapEntry)) { $ret['pm_name'] = $ldapEntry[0]['displayname'][0]; $ret['pm_email'] = $ldapEntry[0]['userprincipalname'][0]; return $ret; } else { throw new Exception('Nie znaleziono użytkownika w domenie!'); } }
/** * init ldap */ protected function _initLdap() { if (!$this->_config->ldap || !$this->_config->ldap->baseDn) { throw new Exception('ldap config section or basedn missing'); } $this->_ldap = new Zend_Ldap($this->_config->ldap->toArray()); $this->_ldap->bind(); $this->_logger->info(__METHOD__ . '::' . __LINE__ . ' LDAP initialized'); }
public function isValid($value) { $config = Zend_Registry::get('config'); $servers = $config['ldap']; $identity = Zend_Auth::getInstance()->getIdentity(); foreach ($servers as $server) { try { $ldap = new Zend_Ldap($server); $bind = $ldap->bind($identity->login, $value); if (!empty($bind)) { return true; } } catch (Exception $e) { $valid = false; } } if (!$valid) { $this->_error(self::NOT_VALID); return false; } }
public function testRequiresDnWithoutDnBind() { $options = $this->_options; /* Fixup filter since bindRequiresDn is used to determine default accountFilterFormat */ if (!isset($options['accountFilterFormat']) && !$this->_bindRequiresDn) { $options['accountFilterFormat'] = '(&(objectClass=user)(sAMAccountName=%s))'; } $options['bindRequiresDn'] = true; unset($options['username']); $ldap = new Zend_Ldap($options); try { $ldap->bind($this->_principalName); } catch (Zend_Ldap_Exception $zle) { /* Note that if your server actually allows anonymous binds this test will fail. */ $this->assertContains('Failed to retrieve DN', $zle->getMessage()); } }
private function registerUserDirectory() { $this[self::USER_DIRECTORY] = function () { $application = EngineBlock_ApplicationSingleton::getInstance(); /** @var Zend_Config $ldapConfig */ $ldapConfig = $application->getConfigurationValue('ldap', null); if (empty($ldapConfig)) { throw new EngineBlock_Exception('No LDAP config'); } $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(); return new EngineBlock_UserDirectory($ldapClient); }; }
public function testInvalidAccountCanon() { $ldap = new Zend_Ldap($this->_options); try { $ldap->bind('invalid', 'invalid'); } catch (Zend_Ldap_Exception $zle) { $msg = $zle->getMessage(); $this->assertTrue(strstr($msg, 'Invalid credentials') || strstr($msg, 'No such object')); } }
/** * @group ZF-8259 */ public function testBoundUserIsReturnedAfterBinding() { $ldap = new Zend_Ldap($this->_options); $ldap->bind(); $this->assertEquals(TESTS_ZEND_LDAP_USERNAME, $ldap->getBoundUser()); }
/** * Check if we can connect to the ldap user factory * */ public function checkUserFactoryLdapConf(&$errors, &$config) { if (!function_exists('ldap_connect')) { $errors[] = array('title' => 'PHP LDAP extension is not installed.', 'msg' => 'Use php5-ldap package on debian'); return; } try { $ldap = new Zend_Ldap($config['user_factory_options']); $ldap->bind(); } catch (Exception $e) { $errors[] = array('title' => 'Can\'t connect to the ldap server', 'msg' => $e->getMessage()); } }
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); } }
/** * Checks the group membership of the bound user * * @param Zend_Ldap $ldap * @param string $canonicalName * @param string $dn * @param array $adapterOptions * @return string|true */ protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, array $adapterOptions) { if ($adapterOptions['group'] === null) { return true; } if ($adapterOptions['memberIsDn'] === false) { $user = $canonicalName; } else { $user = $dn; } /** * @see Zend_Ldap_Filter */ // require_once 'Zend/Ldap/Filter.php'; $groupName = Zend_Ldap_Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']); $membership = Zend_Ldap_Filter::equals($adapterOptions['memberAttr'], $user); $group = Zend_Ldap_Filter::andFilter($groupName, $membership); $groupFilter = $adapterOptions['groupFilter']; if (!empty($groupFilter)) { $group = $group->addAnd($groupFilter); } /* * Fixes problem when authenticated user is not allowed to retrieve * group-membership information. * This requires that the user specified with "username" and "password" * in the Zend_Ldap options is able to retrieve the required information. */ $ldap->bind(); $result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']); if ($result === 1) { return true; } else { return 'Failed to verify group membership with ' . $group->toString(); } }
/** * 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; }
/** * @see https://net.educause.edu/ir/library/pdf/csd4875.pdf */ public function testBindWithNullPassword() { $ldap = new Zend_Ldap($this->_options); $this->setExpectedException('Zend_Ldap_Exception', 'Invalid credentials'); $ldap->bind($this->_altUsername, "invalidpassword"); }
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; } }
/** * Metoda pobierająca dane użytkownika o podanym loginie z domeny * @param string $login * @return array|boolean */ public function getLdapData($login, $ldapPwd) { $login = strtolower($login); $config = Zend_Registry::get('config'); $identity = Zend_Auth::getInstance()->getIdentity(); $ldapServers = $config['ldap']; foreach ($ldapServers as $server) { try { $ldap = new Zend_Ldap($server); $ldap->bind($identity->login, $ldapPwd); $ldapEntry = $ldap->searchEntries(Zend_Ldap_Filter::equals('samaccountname', $login)); if (!empty($ldapEntry)) { return array_shift($ldapEntry); } } catch (Exception $e) { // pusty catch - obsługa braku dostępu do wybranej domeny // na podstawie danych zalogowanego użytkownika } } return false; }
public function testMismatchDomainBind() { $ldap = new Zend_Ldap($this->_options); try { $ldap->bind('BOGUS\\doesntmatter', 'doesntmatter'); } catch (Zend_Ldap_Exception $zle) { $this->assertTrue($zle->getCode() == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH); } }
<?php // Assign a UUID to all users in LDAP /** * 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();