/** * For Bitrix calls. * * @param array &$params * * @return int */ public static function authenticate(&$params) { try { // Import PEAR library gracefully... if (!@(include_once 'Net/LDAP2.php')) { throw new Capall_Ldaper_UnavailableDependencyException('PEAR::Net_LDAP2'); } $ldapConnection = Net_LDAP2::connect(array('host' => COption::GetOptionString('sh.ldaper', 'host'), 'port' => COption::GetOptionInt('sh.ldaper', 'port'), 'binddn' => COption::GetOptionString('sh.ldaper', 'binddn'), 'bindpw' => COption::GetOptionString('sh.ldaper', 'bindpw'))); if (PEAR::isError($ldapConnection)) { throw new Capall_Ldaper_LdapException($ldapConnection); } $ldaper = new self($ldapConnection, new Capall_Ldaper_BitrixUserManager(new CUser(), array_filter(explode(',', COption::GetOptionString('sh.ldaper', 'default_groups', '')), 'trim')), COption::GetOptionString('sh.ldaper', 'basedn'), COption::GetOptionString('sh.ldaper', 'login_attribute'), COption::GetOptionString('sh.ldaper', 'mail_attribute'), COption::GetOptionString('sh.ldaper', 'mail_attribute_index')); $ldapUser = $ldaper->getLdapUser($params['LOGIN']); if ($ldapUser) { if ($ldaper->authenticateUser($ldapUser, $params['PASSWORD'])) { $bitrixUserIdentifier = $ldaper->getBitrixUser($ldapUser); } else { // Authentication failed. May be user not from LDAP? return false; } } else { // User not found. It's normal use case. return; } // Return identifier to Bitrix for authorization. return $bitrixUserIdentifier; } catch (Exception $error) { CEventLog::Log('WARNING', 'USER_LOGIN', 'sh.ldaper', $params['LOGIN'], (string) $error); } }
/** * Create LDAP connection. * * @param array $options * @return Net_LDAP2 */ private function connect($options) { $conn = Net_LDAP2::connect($options); if (Misc::isError($conn)) { throw new AuthException($conn->getMessage(), $conn->getCode()); } return $conn; }
/** * Connect to the database. * * @throws <b>AgaviDatabaseException</b> If a connection could not be * created. * * @author Bram Goessens <*****@*****.**> */ protected function connect() { // determine how to get our parameters $method = $this->getParameter('method', 'normal'); // get parameters switch ($method) { case 'normal': // get parameters normally $host = $this->getParameter('host'); $port = $this->getParameter('port', 389); $version = $this->getParameter('version', 3); $basedn = $this->getParameter('basedn'); $binddn = $this->getParameter('binddn', null); $bindpw = $this->getParameter('bindpw', null); if ($host == null || $port == null || $version == null || $basedn == null) { // missing required dsn parameter $error = 'Database configuration specifies method "normal", but is missing 1 or more parameters. Required parameters are host, port, version, basedn'; throw new AgaviDatabaseException($error); } break; default: // who knows what the user wants... $error = 'Invalid KVDag_LdapDatabase parameter retrieval method "%s"'; $error = sprintf($error, $method); throw new AgaviDatabaseException($error); } // The configuration array: $config = array('host' => $host, 'port' => $port, 'version' => $version, 'basedn' => $basedn); //Connecteer de proxyuser if ($binddn != null && $bindpw != null) { $config['binddn'] = $binddn; $config['bindpw'] = $bindpw; } //Connecteer de authzID gebruiker if (AgaviConfig::get('ldap.proxyAs', false)) { $authzID = AgaviConfig::get('ldap.proxyAs'); $proxy_auth_ctrl = array('oid' => '2.16.840.1.113730.3.4.18', 'value' => "dn:{$authzID}", 'iscritical' => true); $config['options'] = array('LDAP_OPT_SERVER_CONTROLS' => array($proxy_auth_ctrl)); } // Connecting using the configuration: $this->connection = Net_LDAP2::connect($config); // Testing for connection error if (Net_LDAP2::isError($this->connection)) { // the connection's foobar'd $error = 'Failed to create a KVDag_LdapDatabase connection'; throw new AgaviDatabaseException($error); } // make sure the connection went through if ($this->connection === false) { // the connection's foobar'd $error = 'Failed to create a KVDag_LdapDatabase connection'; throw new AgaviDatabaseException($error); } // since we're not an abstraction layer, we copy the connection // to the resource $this->resource =& $this->connection; }
/** * LDAP Password Driver * * Driver for passwords stored in LDAP * This driver use the PEAR Net_LDAP2 class (http://pear.php.net/package/Net_LDAP2). * * @version 1.0 (2009-06-24) * @author Edouard MOREAU <*****@*****.**> * * function hashPassword based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * function randomSalt based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/). * */ function password_save($curpass, $passwd) { $rcmail = rcmail::get_instance(); require_once 'Net/LDAP2.php'; // Building user DN $userDN = str_replace('%login', $_SESSION['username'], $rcmail->config->get('password_ldap_userDN_mask')); $parts = explode('@', $_SESSION['username']); if (count($parts) == 2) { $userDN = str_replace('%name', $parts[0], $userDN); $userDN = str_replace('%domain', $parts[1], $userDN); } if (empty($userDN)) { return PASSWORD_CONNECT_ERROR; } // Connection Method switch ($rcmail->config->get('password_ldap_method')) { case 'user': $binddn = $userDN; $bindpw = $curpass; break; case 'admin': $binddn = $rcmail->config->get('password_ldap_adminDN'); $bindpw = $rcmail->config->get('password_ldap_adminPW'); break; default: $binddn = $userDN; $bindpw = $curpass; break; // default is user mode } // Configuration array $ldapConfig = array('binddn' => $binddn, 'bindpw' => $bindpw, 'basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); // Connecting using the configuration array $ldap = Net_LDAP2::connect($ldapConfig); // Checking for connection error if (PEAR::isError($ldap)) { return PASSWORD_CONNECT_ERROR; } // Crypting new password $newCryptedPassword = hashPassword($passwd, $rcmail->config->get('password_ldap_encodage')); if (!$newCryptedPassword) { return PASSWORD_CRYPT_ERROR; } // Writing new crypted password to LDAP $userEntry = $ldap->getEntry($userDN); if (Net_LDAP2::isError($userEntry)) { return PASSWORD_CONNECT_ERROR; } if (!$userEntry->replace(array($rcmail->config->get('password_ldap_pwattr') => $newCryptedPassword), $rcmail->config->get('password_ldap_force_replace'))) { return PASSWORD_CONNECT_ERROR; } if (Net_LDAP2::isError($userEntry->update())) { return PASSWORD_CONNECT_ERROR; } // All done, no error return PASSWORD_SUCCESS; }
public function Connect() { Log::Debug('Trying to connect to LDAP'); $this->ldap = Net_LDAP2::connect($this->options->Ldap2Config()); if (PEAR::isError($this->ldap)) { $message = 'Could not connect to LDAP server. Check your settings in Ldap.config.php : ' . $this->ldap->getMessage(); Log::Error($message); throw new Exception($message); } return true; }
/** * Establishes a working connection * * @return Net_LDAP2 */ public function &connect() { // Check extension if (true !== Net_LDAP2::checkLDAPExtension()) { $this->markTestSkipped('PHP LDAP extension not found or not loadable. Skipped Test.'); } // Simple working connect and privilegued bind $lcfg = array('host' => $this->ldapcfg['global']['server_address'], 'port' => $this->ldapcfg['global']['server_port'], 'basedn' => $this->ldapcfg['global']['server_base_dn'], 'binddn' => $this->ldapcfg['global']['server_binddn'], 'bindpw' => $this->ldapcfg['global']['server_bindpw'], 'filter' => '(ou=*)'); $ldap = Net_LDAP2::connect($lcfg); $this->assertInstanceOf('Net_LDAP2', $ldap, 'Connect failed but was supposed to work. Check credentials and host address. If those are correct, file a bug!'); return $ldap; }
/** * Create LDAP connection. * * @return Net_LDAP2 */ protected function connect() { static $conn; if (!$conn) { $setup = Setup::get()->ldap; $options = array('host' => $setup['host'], 'port' => $setup['port'], 'binddn' => $setup['binddn'], 'bindpw' => $setup['bindpw'], 'basedn' => $this->basedn); $conn = Net_LDAP2::connect($options); if (Misc::isError($conn)) { throw new AuthException($conn->getMessage(), $conn->getCode()); } } return $conn; }
/** * Bind with searchDN and searchPW and search for the user's DN. * Use search_base and search_filter defined in config file. * Return the found DN. */ function search_userdn($rcmail) { $ldapConfig = array('binddn' => $rcmail->config->get('password_ldap_searchDN'), 'bindpw' => $rcmail->config->get('password_ldap_searchPW'), 'basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); $ldap = Net_LDAP2::connect($ldapConfig); if (PEAR::isError($ldap)) { return ''; } $base = $rcmail->config->get('password_ldap_search_base'); $filter = substitute_vars($rcmail->config->get('password_ldap_search_filter')); $options = array('scope' => 'sub', 'attributes' => array()); $result = $ldap->search($base, $filter, $options); $ldap->done(); if (PEAR::isError($result) || $result->count() != 1) { return ''; } return $result->current()->dn(); }
function connect($user, $passwd) { require_once '/usr/share/pear/Net/LDAP2.php'; $config = array('binddn' => "uid={$user},ou=people,dc=domain,dc=com", 'bindpw' => "{$passwd}", 'basedn' => 'dc=domain,dc=com', 'host' => 'ldaprr.domain.com'); $ldap = Net_LDAP2::connect($config); if (PEAR::isError($ldap)) { //echo 'Could not connect to LDAP-server: '.$ldap->getMessage(); return FALSE; } $filter = 'uid=' . $user; $searchbase = 'dc=domain,dc=com'; $options = array('scope' => 'sub', 'attributes' => array('uid', 'cn')); $result = $ldap->search($searchbase, $filter, $options); $entries = $result->entries(); if (count($entries) != 1) { echo "."; } else { foreach ($entries as $entry) { setcookie('UName', $entry->getValue('cn'), time() + 900); } } return TRUE; }
public function login($queryStr) { // If username and password provided if (isset($queryStr['username']) && isset($queryStr['password'])) { $username = addslashes($queryStr['username']); $password = addslashes($queryStr['password']); // If not already logged in if (!isset($_SESSION['username'])) { $_SESSION['start'] = "login " . $queryStr['username'] . " "; $netLogin = false; if ($this->registry->ldapAuth == true) { $where = "username=?"; $bind = array($username); $result = $this->registry->db->select('User', $where, $bind); // LDAP Authentication $config = array('binddn' => $queryStr['username'] . "@aston.ac.uk", 'bindpw' => $queryStr['password'], 'basedn' => 'dc=campus,dc=aston,dc=ac,dc=uk', 'host' => 'gc.campus.aston.ac.uk', 'port' => '3268'); // Connecting using the configuration: $ldap = Net_LDAP2::connect($config); if ($this->registry->ldapAuth == true && Net_LDAP2::isError($ldap)) { error_log("ldap ERROR=" . $ldap->getMessage()); } else { //error_log("LDAP CONNECTED"); $netLogin = TRUE; } } else { $where = "username=? and password=?"; $bind = array($username, $password); $result = $this->registry->db->select('User', $where, $bind); $netLogin = true; } // If user/pass match a user then set login session if ($netLogin == TRUE && sizeof($result) == 1) { if (!isset($_SESSION["timeout"])) { $_SESSION['timeout'] = time(); } $st = $_SESSION['timeout'] + 3600; //session time is 1 hour $_SESSION['start'] .= "One row "; $row = $result[0]; $_SESSION['start'] .= sizeof($row) . " "; $_SESSION['username'] = $row['username']; $_SESSION['name'] = $row['firstname'] . ' ' . $row['surname']; $where = "username=?"; $bind = array($username); $result = $this->registry->db->select('Admin', $where, $bind); if (sizeof($result) == 1) { $row = $result[0]; $_SESSION['admin'] = true; } $result = $this->registry->db->select('Tutors', $where, $bind); if (sizeof($result) == 1) { $row = $result[0]; $_SESSION['tutor'] = true; } $result = $this->registry->db->select('TeachAssist', $where, $bind); if (sizeof($result) >= 1) { $row = $result[0]; $_SESSION['ta'] = true; } } else { $_SESSION['start'] .= "no rows"; } } } // If login was successful if (isset($_SESSION['username'])) { $_SESSION['invalid_login'] = false; } else { $_SESSION['invalid_login'] = true; } }
/** * Bind with searchDN and searchPW and search for the user's DN. * Use search_base and search_filter defined in config file. * Return the found DN. */ function search_userdn($rcmail) { $binddn = $rcmail->config->get('password_ldap_searchDN'); $bindpw = $rcmail->config->get('password_ldap_searchPW'); $ldapConfig = array('basedn' => $rcmail->config->get('password_ldap_basedn'), 'host' => $rcmail->config->get('password_ldap_host'), 'port' => $rcmail->config->get('password_ldap_port'), 'starttls' => $rcmail->config->get('password_ldap_starttls'), 'version' => $rcmail->config->get('password_ldap_version')); // allow anonymous searches if (!empty($binddn)) { $ldapConfig['binddn'] = $binddn; $ldapConfig['bindpw'] = $bindpw; } $ldap = Net_LDAP2::connect($ldapConfig); if (is_a($ldap, 'PEAR_Error')) { return ''; } $base = self::substitute_vars($rcmail->config->get('password_ldap_search_base')); $filter = self::substitute_vars($rcmail->config->get('password_ldap_search_filter')); $options = array('scope' => 'sub', 'attributes' => array()); $result = $ldap->search($base, $filter, $options); $ldap->done(); if (is_a($result, 'PEAR_Error') || $result->count() != 1) { return ''; } return $result->current()->dn(); }
/** * Check if $user and $password are related to a valid user and password * * @param string $check_password * @return boolean */ function isValidPasswordLdap($user, $password, $config) { // Connecting using the configuration: require_once "Net/LDAP2.php"; $ldap = Net_LDAP2::connect($config); // Testing for connection error if (PEAR::isError($ldap)) { return false; } $filter = Net_LDAP2_Filter::create($config['uid'], 'equals', $user); $search = $ldap->search(null, $filter, null); if (Net_LDAP2::isError($search)) { return false; } if ($search->count() != 1) { return false; } // User exists so we may rebind to authenticate the password $entries = $search->entries(); $bind_result = $ldap->bind($entries[0]->dn(), $password); if (PEAR::isError($bind_result)) { return false; } return true; }
private function init_schema() { // use PEAR include if autoloading failed if (!class_exists('Net_LDAP2')) { require_once 'Net/LDAP2.php'; } $port = $this->config_get('port', 389); $tls = $this->config_get('use_tls', false); foreach ((array) $this->config_get('hosts') as $host) { $this->_debug("C: Connect [{$host}:{$port}]"); $_ldap_cfg = array('host' => $host, 'port' => $port, 'tls' => $tls, 'version' => 3, 'binddn' => $this->config_get('service_bind_dn'), 'bindpw' => $this->config_get('service_bind_pw')); $_ldap_schema_cache_cfg = array('path' => "/tmp/" . $host . ":" . ($port ? $port : '389') . "-Net_LDAP2_Schema.cache", 'max_age' => 86400); $_ldap = Net_LDAP2::connect($_ldap_cfg); if (!is_a($_ldap, 'Net_LDAP2_Error')) { $this->_debug("S: OK"); break; } $this->_debug("S: NOT OK"); $this->_debug($_ldap->getMessage()); } if (is_a($_ldap, 'Net_LDAP2_Error')) { return null; } $_ldap_schema_cache = new Net_LDAP2_SimpleFileSchemaCache($_ldap_schema_cache_cfg); $_ldap->registerSchemaCache($_ldap_schema_cache); // TODO: We should learn what LDAP tech. we're running against. // Perhaps with a scope base objectclass recognize rootdse entry $schema_root_dn = $this->config_get('schema_root_dn'); if (!$schema_root_dn) { $_schema = $_ldap->schema(); } return $_schema; }
/** * Main Authentication method * Required for plugin interface * @param unknown $login User's username * @param unknown $password User's password * @return boolean */ function authenticate($login, $password) { if ($login && $password) { if (!function_exists('ldap_connect')) { trigger_error('auth_ldap requires PHP\'s PECL LDAP package installed.'); return FALSE; } if (!(require_once 'Net/LDAP2.php')) { trigger_error('auth_ldap requires the PEAR package Net::LDAP2'); return FALSE; } /** Loading configuration **/ $this->_debugMode = defined('LDAP_AUTH_DEBUG') ? LDAP_AUTH_DEBUG : FALSE; $this->_anonBeforeBind = defined('LDAP_AUTH_ANONYMOUSBEFOREBIND') ? LDAP_AUTH_ANONYMOUSBEFOREBIND : FALSE; $this->_serviceBindDN = defined('LDAP_AUTH_BINDDN') ? LDAP_AUTH_BINDDN : null; $this->_serviceBindPass = defined('LDAP_AUTH_BINDPW') ? LDAP_AUTH_BINDPW : null; $this->_baseDN = defined('LDAP_AUTH_BASEDN') ? LDAP_AUTH_BASEDN : null; if (!defined('LDAP_AUTH_BASEDN')) { $this->_log('LDAP_AUTH_BASEDN is required and not defined.', E_USER_ERROR); return FALSE; } else { $this->_baseDN = LDAP_AUTH_BASEDN; } $parsedURI = parse_url(LDAP_AUTH_SERVER_URI); if ($parsedURI === FALSE) { $this->_log('Could not parse LDAP_AUTH_SERVER_URI in config.php', E_USER_ERROR); return FALSE; } $this->_host = $parsedURI['host']; $this->_scheme = $parsedURI['scheme']; if (is_int($parsedURI['port'])) { $this->_port = $parsedURI['port']; } else { $this->_port = $this->_scheme === 'ldaps' ? 636 : 389; } $this->_useTLS = defined('LDAP_AUTH_USETLS') ? LDAP_AUTH_USETLS : FALSE; $this->_allowUntrustedCerts = defined('LDAP_AUTH_ALLOW_UNTRUSTED_CERT') ? LDAP_AUTH_ALLOW_UNTRUSTED_CERT : FALSE; $this->_schemaCacheEnable = defined('LDAP_AUTH_SCHEMA_CACHE_ENABLE') ? LDAP_AUTH_SCHEMA_CACHE_ENABLE : TRUE; $this->_schemaCacheTimeout = defined('LDAP_AUTH_SCHEMA_CACHE_TIMEOUT') ? LDAP_AUTH_SCHEMA_CACHE_TIMEOUT : 86400; $this->_logAttempts = defined('LDAP_AUTH_LOG_ATTEMPTS') ? LDAP_AUTH_LOG_ATTEMPTS : FALSE; $this->_ldapLoginAttrib = defined('LDAP_AUTH_LOGIN_ATTRIB') ? LDAP_AUTH_LOGIN_ATTRIB : null; /** Building LDAP connection **/ $ldapConnParams = array('host' => $this->_scheme . '://' . $this->_host, 'options' => array('LDAP_OPT_REFERRALS' => 0), 'basedn' => $this->_baseDN, 'port' => $this->_port, 'starttls' => $this->_useTLS); if (!$this->_anonBeforeBind) { $ldapConnParams['binddn'] = $this->_serviceBindDN; $ldapConnParams['bindpw'] = $this->_serviceBindPass; } if ($this->_allowUntrustedCerts) { putenv('LDAPTLS_REQCERT=never'); } if ($this->_debugMode) { $this->_log(print_r($ldapConnParams, TRUE), E_USER_NOTICE); } $ldapConn = Net_LDAP2::connect($ldapConnParams); if (get_class($ldapConn) !== 'Net_LDAP2') { $this->_log('Could not connect to LDAP Server: ' . $ldapConn->getMessage() . ' with ' . $this->_getBindDNWord(), E_USER_ERROR); return FALSE; } else { $this->ldapObj = $ldapConn; $this->_log('Connected to LDAP Server: ' . LDAP_AUTH_SERVER_URI . ' with ' . $this->_getBindDNWord()); } // Bind with service account if orignal connexion was anonymous if ($this->_anonBeforeBind && strlen($this->_bindDN > 0)) { $binding = $this->ldapObj->bind($this->_serviceBindDN, $this->_serviceBindPass); if (get_class($binding) !== 'Net_LDAP2') { $this->_log('Cound not bind service account: ' . $binding->getMessage(), E_USER_ERROR); return FALSE; } else { $this->_log('Bind with ' . $this->_serviceBindDN . ' successful.', E_USER_NOTICE); } } //Cache LDAP Schema if ($ldapSchemaCacheEnable) { $this->_getSchemaCache(); } //Validate BaseDN $baseDNObj = $this->ldapObj->getEntry($this->_baseDN); if (get_class($baseDNObj) !== 'Net_LDAP2_Entry') { $this->_log('Cound not get LDAP_AUTH_BASEDN. Please check config.php', E_USER_ERROR); //return FALSE; } //Searching for user $escapedUserName = Net_LDAP2_Util::escape_filter_value(array($login)); $completedSearchFilter = str_replace('???', $escapedUserName[0], LDAP_AUTH_SEARCHFILTER); $filterObj = Net_LDAP2_Filter::parse($completedSearchFilter); if (get_class($filterObj) !== 'Net_LDAP2_Filter') { $this->_log('Could not parse LDAP Search filter', E_USER_ERROR); return FALSE; } if ($this->_debugMode) { $this->_log("Seaching for user {$login} with this query " . $filterObj->asString() . ' within ' . $this->_baseDN); } $searchResults = $this->ldapObj->search($this->_baseDN, $filterObj); if (get_class($searchResults) !== 'Net_LDAP2_Search') { $this->_log('LDAP Search Failed: ' . $searchResults->getMessage(), E_USER_ERROR); return FALSE; } elseif ($searchResults->count() === 0) { $this->_log((string) $login, 'Unknown User', E_USER_NOTICE); return FALSE; } elseif ($searchResults->count() > 1) { $this->_log('Multiple DNs found for username ' . (string) $login, E_USER_WARNING); return FALSE; } //Getting user's DN from search $userEntry = $searchResults->shiftEntry(); $userDN = $userEntry->dn(); //Binding with user's DN. if ($this->_debugMode) { $this->_log('Try to bind with user\'s DN: ' . $userDN); } $loginAttempt = $this->ldapObj->bind($userDN, $password); if ($loginAttempt === TRUE) { $this->_log('User: '******' authentication successful'); if (strlen($this->_ldapLoginAttrib) > 0) { if ($this->_debugMode) { $this->_log('Looking up TT-RSS username attribute in ' . $this->_ldapLoginAttrib); } $ttrssUsername = $userEntry->getValue($this->_ldapLoginAttrib, 'single'); $this->ldapObj->disconnect(); if (!is_string($ttrssUsername)) { $this->_log('Could not find user name attribute ' . $this->_ldapLoginAttrib . ' in LDAP entry', E_USER_WARNING); return FALSE; } return $this->base->auto_create_user($ttrssUsername); } else { $this->ldapObj->disconnect(); return $this->base->auto_create_user($login); } } elseif ($loginAttempt->getCode() == 49) { $this->ldapObj->disconnect(); $this->_log('User: '******' authentication failed'); return FALSE; } else { $this->ldapObj->disconnect(); $this->_log('Unknown Error: Code: ' . $loginAttempt->getCode() . ' Message: ' . $loginAttempt->getMessage() . ' user(' . (string) $login . ')', E_USER_WARNING); return FALSE; } } return false; }
function authenticate($login, $password) { if ($login && $password) { if (!function_exists('ldap_connect')) { trigger_error('auth_ldap requires PHP\'s PECL LDAP package installed.'); return FALSE; } if (!(require_once 'Net/LDAP2.php')) { trigger_error('auth_ldap requires the PEAR package Net::LDAP2'); return FALSE; } $debugMode = defined('LDAP_AUTH_DEBUG') ? LDAP_AUTH_DEBUG : FALSE; $anonymousBeforeBind = defined('LDAP_AUTH_ANONYMOUSBEFOREBIND') ? LDAP_AUTH_ANONYMOUSBEFOREBIND : FALSE; $parsedURI = parse_url(LDAP_AUTH_SERVER_URI); if ($parsedURI === FALSE) { $this->_log('Could not parse LDAP_AUTH_SERVER_URI in config.php'); return FALSE; } $ldapConnParams = array('host' => $parsedURI['scheme'] . '://' . $parsedURI['host'], 'basedn' => LDAP_AUTH_BASEDN, 'options' => array('LDAP_OPT_REFERRALS' => 0)); if (!$anonymousBeforeBind) { $ldapConnParams['binddn'] = LDAP_AUTH_BINDDN; $ldapConnParams['bindpw'] = LDAP_AUTH_BINDPW; } $ldapConnParams['starttls'] = defined('LDAP_AUTH_USETLS') ? LDAP_AUTH_USETLS : FALSE; if (is_int($parsedURI['port'])) { $ldapConnParams['port'] = $parsedURI['port']; } $ldapSchemaCacheEnable = defined('LDAP_AUTH_SCHEMA_CACHE_ENABLE') ? LDAP_AUTH_SCHEMA_CACHE_ENABLE : TRUE; $ldapSchemaCacheTimeout = defined('LDAP_AUTH_SCHEMA_CACHE_TIMEOUT') ? LDAP_AUTH_SCHEMA_CACHE_TIMEOUT : 86400; $logAttempts = defined('LDAP_AUTH_LOG_ATTEMPTS') ? LDAP_AUTH_LOG_ATTEMPTS : FALSE; // Making connection to LDAP server if (LDAP_AUTH_ALLOW_UNTRUSTED_CERT === TRUE) { putenv('LDAPTLS_REQCERT=never'); } $ldapConn = Net_LDAP2::connect($ldapConnParams); if (Net_LDAP2::isError($ldapConn)) { $this->_log('Could not connect to LDAP Server: ' . $ldapConn->getMessage()); return FALSE; } // Bind with service account if orignal connexion was anonymous if ($anonymousBeforeBind) { $binding = $ldapConn->bind(LDAP_AUTH_BINDDN, LDAP_AUTH_BINDPW); if (Net_LDAP2::isError($binding)) { $this->_log('Cound not bind service account: ' . $binding->getMessage()); return FALSE; } } //Cache LDAP Schema if ($ldapSchemaCacheEnable) { if (!sys_get_temp_dir()) { $tmpFile = tmp; $tmpDir = dirname($tmpFile); unlink($tmpFile); unset($tmpFile); } else { $tmpDir = sys_get_temp_dir(); } if (empty($parsedURI['port'])) { $ldapPort = $parsedURI['scheme'] == 'ldaps' ? 636 : 389; } else { $ldapPort = $parsedURI['port']; } $cacheFileLoc = $tmpDir . '/ttrss-ldapCache-' . $parsedURI['host'] . ':' . $ldapPort . '.cache'; if ($debugMode) { $this->_log('Schema Cache File: ' . $cacheFileLoc, E_USER_NOTICE); } $schemaCacheConf = array('path' => $cacheFileLoc, 'max_age' => $ldapSchemaCacheTimeout); $schemaCacheObj = new Net_LDAP2_SimpleFileSchemaCache($schemaCacheConf); $ldapConn->registerSchemaCache($schemaCacheObj); $schemaCacheObj->storeSchema($ldapConn->schema()); } //Searching for user $completedSearchFiler = str_replace('???', $login, LDAP_AUTH_SEARCHFILTER); $filterObj = Net_LDAP2_Filter::parse($completedSearchFiler); $searchResults = $ldapConn->search(LDAP_AUTH_BASEDN, $filterObj); if (Net_LDAP2::isError($searchResults)) { $this->_log('LDAP Search Failed: ' . $searchResults->getMessage()); return FALSE; } elseif ($searchResults->count() === 0) { if ($logAttempts) { $this->_logAttempt((string) $login, 'Unknown User'); } return FALSE; } elseif ($searchResults->count() > 1) { $this->_log('Multiple DNs found for username ' . $login); return FALSE; } //Getting user's DN from search $userEntry = $searchResults->shiftEntry(); $userDN = $userEntry->dn(); //Binding with user's DN. $loginAttempt = $ldapConn->bind($userDN, $password); $ldapConn->disconnect(); if ($loginAttempt === TRUE) { if ($logAttempts) { $this->_logAttempt((string) $login, 'successful'); } return $this->base->auto_create_user($login); } elseif ($loginAttempt->getCode() == 49) { if ($logAttempts) { $this->_logAttempt((string) $login, 'bad password'); } return FALSE; } else { $this->_log('Unknown Error: Code: ' . $loginAttempt->getCode() . ' Message: ' . $loginAttempt->getMessage() . ' user(' . (string) $login . ')'); return FALSE; } } return false; }
function vacation_write(array &$data) { require_once 'Net/LDAP2.php'; $rcmail = rcmail::get_instance(); $search = array('%username', '%email_local', '%email_domain', '%email'); $replace = array($data['username'], $data['email_local'], $data['email_domain'], $data['email']); $ldap_basedn = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_basedn')); $ldap_binddn = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_binddn')); $search = array('%username', '%password', '%email_local', '%email_domain', '%email'); $replace = array($data['username'], $rcmail->decrypt($_SESSION['password']), $data['email_local'], $data['email_domain'], $data['email']); $ldap_bindpw = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_bindpw')); $ldapConfig = array('host' => $rcmail->config->get('vacation_ldap_host'), 'port' => $rcmail->config->get('vacation_ldap_port'), 'starttls' => $rcmail->config->get('vacation_ldap_starttls'), 'version' => $rcmail->config->get('vacation_ldap_version'), 'basedn' => $ldap_basedn, 'binddn' => $ldap_binddn, 'bindpw' => $ldap_bindpw); $ldap = Net_LDAP2::connect($ldapConfig); if (PEAR::isError($ldap)) { return PLUGIN_ERROR_CONNECT; } $searchkeys = array('%username', '%email_local', '%email_domain', '%email', '%vacation_enable', '%vacation_start', '%vacation_end', '%vacation_subject', '%vacation_message', '%vacation_keepcopyininbox', '%vacation_forwarder'); $replaceby = array($data['username'], $data['email_local'], $data['email_domain'], $data['email'], $data['vacation_enable'] ? $rcmail->config->get('vacation_ldap_attr_vacationenable_value_enabled') : $rcmail->config->get('vacation_ldap_attr_vacationenable_value_disabled'), $rcmail->config->get('vacation_ldap_date_use_generalized_time_format') ? timestamp2generalizedtime($data['vacation_start']) : $data['vacation_start'], $rcmail->config->get('vacation_ldap_date_use_generalized_time_format') ? timestamp2generalizedtime($data['vacation_end']) : $data['vacation_end'], $data['vacation_subject'], $data['vacation_message'], $data['vacation_keepcopyininbox'], $data['vacation_forwarder']); $dns = $rcmail->config->get('vacation_ldap_modify_dns'); $ops = $rcmail->config->get('vacation_ldap_modify_ops'); if (!empty($dns)) { for ($i = 0; $i < count($dns) && $i < count($ops); $i++) { $dns[$i] = str_replace($searchkeys, $replaceby, $dns[$i]); foreach ($ops[$i] as $op => $args) { foreach ($args as $key => $value) { $ops[$i][$op][$key] = str_replace($searchkeys, $replaceby, $value); } } $ret = $ldap->modify($dns[$i], $ops[$i]); if (PEAR::isError($ret)) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } } } else { $search_base = str_replace($searchkeys, $replaceby, $rcmail->config->get('vacation_ldap_search_base')); $search_filter = str_replace($searchkeys, $replaceby, $rcmail->config->get('vacation_ldap_search_filter')); $search_params = array('attributes' => $rcmail->config->get('vacation_ldap_search_attrs'), 'scope' => $rcmail->config->get('vacation_ldap_search_scope')); $search = $ldap->search($search_base, $search_filter, $search_params); if (PEAR::isError($search)) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } if ($search->count() < 1) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } $entry = $search->shiftEntry(); foreach ($ops as $op => $args) { if (in_array($op, array('add', 'replace', 'delete'))) { foreach ($args as $key => $value) { $value = str_replace($searchkeys, $replaceby, $value); $ret = $entry->{$op}(array($key => $value)); if (PEAR::isError($ret)) { return PLUGIN_ERROR_PROCESS; } } } else { return PLUGIN_ERROR_PROCESS; } } $ret = $entry->update(); if (PEAR::isError($ret)) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } } $ldap->done(); return PLUGIN_SUCCESS; }
define('LDAP_LAYER', getenv('PHP_PEAR_XML_QUERY2XML_TEST_LDAPLAYER')); } else { if (@(include_once 'Net/LDAP2.php')) { define('LDAP_LAYER', 'LDAP2'); } else { define('LDAP_LAYER', 'LDAP'); } } } if (LDAP_LAYER == 'LDAP2') { if (!@(include_once 'Net/LDAP2.php')) { print 'skip could not find Net/LDAP2.php'; exit; } else { include_once dirname(dirname(__FILE__)) . '/settings.php'; $ldap = Net_LDAP2::connect($ldapConfig); if (PEAR::isError($ldap)) { print 'skip could not connect to LDAP directory'; exit; } } } else { if (!@(include_once 'Net/LDAP.php')) { print 'skip could not find Net/LDAP.php'; exit; } else { include_once dirname(dirname(__FILE__)) . '/settings.php'; $ldap = Net_LDAP::connect($ldapConfig); if (PEAR::isError($ldap)) { print 'skip could not connect to LDAP directory'; exit;
public function login() { global $tables; if (!class_exists('Net_LDAP2')) { require getConfig('casldap_netldap2_path'); } self::init_cas_client(); // force CAS authentication phpCAS::forceAuthentication(); $cas_login = phpCAS::getUser(); if (!$cas_login) { return; } $ldap_config = array('host' => getConfig('ldap_host'), 'port' => getConfig('ldap_port'), 'basedn' => getConfig('ldap_basedn')); $ldap_version = getConfig('ldap_version'); if (is_int($ldap_version)) { $ldap_config['version'] = $ldap_version; } if (getConfig('ldap_starttls')) { $ldap_config['starttls'] = true; } $ldap_binddn = getConfig('ldap_binddn'); $ldap_bindpw = getConfig('ldap_bindpw'); if ($ldap_binddn && $ldap_bindpw) { $ldap_config['binddn'] = $ldap_binddn; $ldap_config['bindpw'] = $ldap_bindpw; } $ldap = Net_LDAP2::connect($ldap_config); if (Net_LDAP2::isError($ldap)) { die(Fatal_Error(s("Could not connect to LDAP-server: %s", $ldap->getMessage()))); } $user_filter = str_replace('%login', $cas_login, getConfig('ldap_search_user_filter')); $user_basedn = getConfig('ldap_search_user_basedn'); if (!$user_basedn) { $user_basedn = NULL; } $user_scope = getConfig('ldap_search_user_scope'); if (!in_array($user_scope, array('one', 'base', 'sub'))) { $user_scope = 'sub'; } $user_login_attr = getConfig('ldap_search_user_login_attr'); $user_mail_attr = getConfig('ldap_search_user_mail_attr'); $options = array('scope' => $user_scope, 'attributes' => array($user_mail_attr)); if ($user_login_attr) { $options['attributes'][] = $user_login_attr; } $search = $ldap->search($user_basedn, $user_filter, $options); if (Net_LDAP2::isError($search)) { die(Fatal_Error(s("A problem occured during user search in LDAP : %s", $search->getMessage()))); } if ($search->count() == 0) { die(Error(s("You are not authorized to access to this page"))); } elseif ($search->count() != 1) { die(Fatal_Error(s("Found %d users in LDAP corresponding to CAS login %s.", $search->count(), $cas_login))); } $user_entry = $search->shiftEntry(); if ($user_login_attr) { $login = $user_entry->getValue($user_login_attr, 'single'); if (!is_string($login)) { die(Fatal_Error(s("Fail to retreive user login from LDAP data"))); } } else { $login = $cas_login; } $mail = $user_entry->getValue($user_mail_attr, 'single'); if (!is_string($mail)) { die(Fatal_Error(s("Fail to retreive user mail from LDAP data"))); } $superuser = 0; $superuser_filter = getConfig('ldap_search_superuser_filter'); if ($superuser_filter) { $superuser_filter = str_replace('%login', $login, $superuser_filter); $superuser_basedn = getConfig('ldap_search_superuser_basedn'); if (!$superuser_basedn) { $superuser_basedn = NULL; } $superuser_scope = getConfig('ldap_search_superuser_scope'); if (!in_array($superuser_scope, array('one', 'base', 'sub'))) { $superuser_scope = 'sub'; } $search = $ldap->search($superuser_basedn, $superuser_filter, array('scope' => $superuser_scope, 'attrsonly' => true)); if (Net_LDAP2::isError($search)) { die(Fatal_Error(s("A problem occured during the search in LDAP to known if user is a superuser : %s", $search->getMessage()))); } if ($search->count() > 0) { $superuser = 1; } } elseif (getConfig('casldap_all_user_superadmin')) { $superuser = 1; } $row = Sql_Fetch_Row_Query(sprintf("SELECT id, privileges\n\t\t\tFROM {$tables['admin']}\n\t\t\tWHERE loginname = '%s'", sql_escape($login))); if ($row) { list($id, $privileges) = $row; $update = Sql_Query(sprintf("UPDATE {$tables['admin']} SET\n\t\t\t\temail = '%s',\n\t\t\t\tsuperuser = %s,\n\t\t\t\tdisabled = 0\n\t\t\t\tWHERE id=%s", sql_escape($mail), $superuser, $id)); if (!$update) { die(Fatal_Error(s("Fail to update user informations in database : %s", Sql_Error()))); } } else { $insert = Sql_Query(sprintf("INSERT INTO {$tables['admin']}\n\t\t\t\t(loginname,email,superuser,disabled)\n\t\t\t\tVALUES\n\t\t\t\t('%s','%s',%s,0)", sql_escape($login), sql_escape($mail), $superuser)); if (!$insert) { die(Fatal_Error(s("Fail to create user in database : %s", Sql_Error()))); } $id = Sql_Insert_Id(); } $_SESSION['adminloggedin'] = $_SERVER["REMOTE_ADDR"]; $_SESSION['logindetails'] = array('adminname' => $login, 'id' => $id, 'superuser' => $superuser); if ($privileges) { $_SESSION['privileges'] = unserialize($privileges); } if (isset($_GET['ticket'])) { header('Location: ' . $_SERVER['REQUEST_URI']); exit; } return true; }
/** * testStartTLS() if server supports it */ public function testStartTLS() { // Check extension if (true !== Net_LDAP2::checkLDAPExtension()) { $this->markTestSkipped('PHP LDAP extension not found or not loadable. Skipped Test.'); } if (!$this->ldapcfg) { $this->markTestSkipped('No ldapconfig.ini found. Skipping test!'); } elseif ($this->ldapcfg['global']['server_cap_tls'] == true) { // Simple working connect and privilegued bind $lcfg = array('host' => $this->ldapcfg['global']['server_address'], 'port' => $this->ldapcfg['global']['server_port'], 'binddn' => $this->ldapcfg['global']['server_binddn'] . ',' . $this->ldapcfg['global']['server_binddn'], 'bindpw' => $this->ldapcfg['global']['server_bindpw'], 'starttls' => true); $ldap = Net_LDAP2::connect(); $this->assertInstanceOf('Net_LDAP2', $ldap, 'Connect failed but was supposed to work. Check credentials and host address. If those are correct, file a bug!'); } else { $this->markTestSkipped('Server does not support TLS (see ldapconfig.ini). Skipping test.'); } }
public function bind($reconnect = false) { global $prefs; // Force the reconnection if ($this->ldaplink instanceof Net_LDAP2) { if ($reconnect === true) { $this->ldaplink->disconnect(); } else { return true; // do not try to reconnect since this may lead to huge timeouts } } // Set the bindpw with the options['password'] if ($this->options['bind_type'] != 'explicit') { $this->options['bindpw'] = $this->options['password']; } $user = $this->options['username']; switch ($this->options['bind_type']) { case 'ad': // active directory preg_match_all('/\\s*,?dc=\\s*([^,]+)/i', $this->options['basedn'], $t); $this->options['binddn'] = $user . '@'; if (isset($t[1]) && is_array($t[1])) { foreach ($t[1] as $domainpart) { $this->options['binddn'] .= $domainpart . '.'; } // cut trailing dot $this->options['binddn'] = substr($this->options['binddn'], 0, -1); } // set referrals to 0 to avoid LDAP_OPERATIONS_ERROR $this->options['options']['LDAP_OPT_REFERRALS'] = 0; break; case 'plain': // plain username $this->options['binddn'] = $user; break; case 'full': $this->options['binddn'] = $this->user_dn($user); break; case 'ol': // openldap $this->options['binddn'] = 'cn=' . $user . ',' . $prefs['auth_ldap_basedn']; break; case 'default': // Anonymous binding $this->options['binddn'] = ''; $this->options['bindpw'] = ''; break; case 'explicit': break; default: $this->add_log('ldap', 'Error: Invalid "bind_type" value "' . $this->options['bind_type'] . '".'); die; } $this->add_log('ldap', 'Connect Host: ' . implode($this->options['host']) . '. Binddn: ' . $this->options['binddn'] . ' at line ' . __LINE__ . ' in ' . __FILE__); //create options array to handle it to Net_LDAP2 foreach (array('host', 'port', 'version', 'starttls', 'basedn', 'filter', 'scope', 'binddn', 'bindpw', 'options') as $o) { if (isset($this->options[$o])) { $options[$o] = $this->options[$o]; } } $this->ldaplink = Net_LDAP2::connect($options); if (Net_LDAP2::isError($this->ldaplink)) { $this->add_log('ldap', 'Error: ' . $this->ldaplink->getMessage() . ' at line ' . __LINE__ . ' in ' . __FILE__); // return Net_LDAP2 Error codes. No need to redefine this. return $this->ldaplink->getCode(); } return 'LDAP_SUCCESS'; }
function vacation_write(array &$data) { require_once 'Net/LDAP2.php'; $rcmail = rcmail::get_instance(); $search = array('%username', '%email_local', '%email_domain', '%email'); $replace = array($data['username'], $data['email_local'], $data['email_domain'], $data['email']); $ldap_basedn = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_basedn')); $ldap_binddn = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_binddn')); $search = array('%username', '%password', '%email_local', '%email_domain', '%email'); $replace = array($data['username'], $rcmail->decrypt($_SESSION['password']), $data['email_local'], $data['email_domain'], $data['email']); $ldap_bindpw = str_replace($search, $replace, $rcmail->config->get('vacation_ldap_bindpw')); $ldapConfig = array('host' => $rcmail->config->get('vacation_ldap_host'), 'port' => $rcmail->config->get('vacation_ldap_port'), 'starttls' => $rcmail->config->get('vacation_ldap_starttls'), 'version' => $rcmail->config->get('vacation_ldap_version'), 'basedn' => $ldap_basedn, 'binddn' => $ldap_binddn, 'bindpw' => $ldap_bindpw); $ldap = Net_LDAP2::connect($ldapConfig); if (PEAR::isError($ldap)) { return PLUGIN_ERROR_CONNECT; } $dns = $rcmail->config->get('vacation_ldap_modify_dns'); $ops = $rcmail->config->get('vacation_ldap_modify_ops'); for ($i = 0; $i < count($dns) && $i < count($ops); $i++) { $search = array('%username', '%email_local', '%email_domain', '%email', '%vacation_enable', '%vacation_start', '%vacation_end', '%vacation_subject', '%vacation_message', '%vacation_keepcopyininbox', '%vacation_forwarder'); $replace = array($data['username'], $data['email_local'], $data['email_domain'], $data['email'], $data['vacation_enable'] ? "TRUE" : "FALSE", $data['vacation_start'], $data['vacation_end'], $data['vacation_subject'], $data['vacation_message'], $data['vacation_keepcopyininbox'], $data['vacation_forwarder']); $dns[$i] = str_replace($search, $replace, $dns[$i]); foreach ($ops[$i] as $op => $args) { foreach ($args as $key => $value) { $search = array('%username', '%email_local', '%email_domain', '%email', '%vacation_enable', '%vacation_start', '%vacation_end', '%vacation_subject', '%vacation_message', '%vacation_keepcopyininbox', '%vacation_forwarder'); $replace = array($data['username'], $data['email_local'], $data['email_domain'], $data['email'], $data['vacation_enable'] ? $rcmail->config->get('vacation_ldap_attr_vacationenable_value_enabled') : $rcmail->config->get('vacation_ldap_attr_vacationenable_value_disabled'), $data['vacation_start'], $data['vacation_end'], $data['vacation_subject'], $data['vacation_message'], $data['vacation_keepcopyininbox'], $data['vacation_forwarder']); $ops[$i][$op][$key] = str_replace($search, $replace, $value); } } $ret = $ldap->modify($dns[$i], $ops[$i]); if (PEAR::isError($ldap)) { $ldap->done(); return PLUGIN_ERROR_PROCESS; } } $ldap->done(); return PLUGIN_SUCCESS; }