private function changeOpenLDAPPwd($objLdapBinding, $strUserDN, $strNewPwd) { include_once "sambahash.php"; $entry["sambaNTPassword"] = nt_hash($strNewPwd); $this->logwriter->debugwrite('NT Hash:' . $entry["sambaNTPassword"]); $entry["sambaLMPassword"] = lm_hash($strNewPwd); $this->logwriter->debugwrite('LM Hash:' . $entry["sambaLMPassword"]); $date = time(); $this->logwriter->debugwrite('Last Set:' . $date); $entry["sambaPwdLastSet"] = $date; $entry["sambaPwdMustChange"] = $date + 90 * 24 * 60 * 60; $this->logwriter->debugwrite('Must Change:' . $entry["sambaPwdMustChange"]); mt_srand((double) microtime() * 1000000); $salt = pack("CCCC", mt_rand(), mt_rand(), mt_rand(), mt_rand()); $hash = "{SSHA}" . base64_encode(pack("H*", sha1($strNewPwd . $salt)) . $salt); $entry["userPassword"] = $hash; $entry["shadowLastChange"] = (int) ($date / 86400); $this->logwriter->debugwrite('Shadow Last Change:' . $entry["shadowLastChange"]); $res = ldap_mod_replace($objLdapBinding, $strUserDN, $entry) or $res = false; if ($res) { $this->success($strNewPwd); return true; } else { //Failed to change user Password $this->failure(8, array($strNewPwd, $newpass, ldap_error($objLdapBinding))); return false; } }
/** * @return string[] * @throws ValueRetrievalFailureException */ public function parse() { if (!ldap_parse_reference($this->link, $this->reference, $referrals)) { throw new ValueRetrievalFailureException(ldap_error($this->link), ldap_errno($this->link)); } return $referrals; }
/** * {@inheritdoc} */ public function remove(Entry $entry) { $con = $this->connection->getResource(); if (!@ldap_delete($con, $entry->getDn())) { throw new LdapException(sprintf('Could not remove entry "%s": %s', $entry->getDn(), ldap_error($con))); } }
public function __construct($message, $handler, $extra_error = null) { $this->handler = $handler; $err_no = ldap_errno($handler); $message = sprintf("ERROR %s. LDAP ERROR (%s) -- %s --. %s", $message, $err_no, $this->getErrorStr(), ldap_error($handler), is_null($extra_error) ? '' : $extra_error); parent::__construct($message, $err_no); }
function check_LDAP_user($username, $password, $ladpserver, $domain1, $domain2) { global $db1, $_POST, $_SESSION; //echo "!$ladpserver,$domain1,$domain2!"; $HDR_ERR = ""; if (!$password or !$username) { $HDR_ERR = "false"; } else { $filter = "(&(objectClass=top)(sAMAccountName=" . $username . "))"; $basedn = 'dc=$domain1,dc=$domain2'; $dn = "{$domain1}\\{$username}"; $ldapconn = ldap_connect("{$ladpserver}"); ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); if (!$ldapconn) { $HDR_ERR .= ldap_error($ldapconn); } else { $bind = @ldap_bind($ldapconn, $dn, $password); if ($bind == "1") { $HDR_ERR = 'true'; } else { $HDR_ERR = "false"; } } } return $HDR_ERR; }
public function rewind() { $this->current = ldap_first_entry($this->connection, $this->search); if (false === $this->current) { throw new LdapException(sprintf('Could not rewind entries array: %s', ldap_error($this->connection))); } }
function change_pass($user, $new_pass) { global $config; global $ldap_connection; get_ldap_connection($config['user'], $config['pass']); if ($ldap_connection) { $filter = "(sAMAccountName={$user})"; $result = ldap_search($ldap_connection, $config['domain_dn'], $filter); ldap_sort($ldap_connection, $result, "sn"); $info = ldap_get_entries($ldap_connection, $result); $isLocked = $info[0]["lockoutTime"]; if ($isLocked > 0) { return msg('account_locked'); } $userDn = $info[0]["distinguishedname"][0]; $userdata["unicodePwd"] = iconv("UTF-8", "UTF-16LE", '"' . $new_pass . '"'); $result = ldap_mod_replace($ldap_connection, $userDn, $userdata); if (!$result) { return msg(ldap_error($ldap_connection)); } } else { return msg("wrong_admin"); } close_ldap_connection(); return ""; }
function ldap_login($username, $password) { $ldapServer = "ldap.iitm.ac.in"; $ldapPort = 389; $ldapDn = "cn=students,ou=bind,dc=ldap,dc=iitm,dc=ac,dc=in"; $ldapPass = "******"; $ldapConn = ldap_connect($ldapServer, $ldapPort) or die("Could not connect to LDAP server."); echo $ldapConn; $studentUser = $username; $studentPass = $password; if ($ldapConn) { $ldapBind = @ldap_bind($ldapConn, $ldapDn, $ldapPass); if ($ldapBind) { $filter = "(&(objectclass=*)(uid=" . $studentUser . "))"; $ldapDn = "dc=ldap,dc=iitm,dc=ac,dc=in"; $result = @ldap_search($ldapConn, $ldapDn, $filter) or die("Error in search query: " . ldap_error($ldapConn)); $entries = @ldap_get_entries($ldapConn, $result); foreach ($entries as $values => $values1) { $logindn = $values1['dn']; } $loginbind = @ldap_bind($ldapConn, $logindn, $studentPass); if ($loginbind) { return 1; } } } @ldap_unbind($ldapConn); return 0; }
function authenticate($username, $password) { global $config, $ldap_connection; if ($username && $ldap_connection) { if ($config['auth_ldap_version']) { ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, $config['auth_ldap_version']); } if (ldap_bind($ldap_connection, $config['auth_ldap_prefix'] . $username . $config['auth_ldap_suffix'], $password)) { if (!$config['auth_ldap_group']) { return 1; } else { $ldap_groups = get_group_list(); foreach ($ldap_groups as $ldap_group) { $ldap_comparison = ldap_compare($ldap_connection, $ldap_group, $config['auth_ldap_groupmemberattr'], get_membername($username)); if ($ldap_comparison === true) { return 1; } } } } else { echo ldap_error($ldap_connection); } } else { // FIXME return a warning that LDAP couldn't connect? } return 0; }
/** * * Verifies a username handle and password. * * @return mixed An array of verified user information, or boolean false * if verification failed. * * */ protected function _processLogin() { // connect $conn = @ldap_connect($this->_config['uri']); // did the connection work? if (!$conn) { throw $this->_exception('ERR_CONNECTION_FAILED', $this->_config); } // upgrade to LDAP3 when possible @ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3); // filter the handle to prevent LDAP injection $regex = '/[^' . $this->_config['filter'] . ']/'; $this->_handle = preg_replace($regex, '', $this->_handle); // bind to the server $rdn = sprintf($this->_config['format'], $this->_handle); $bind = @ldap_bind($conn, $rdn, $this->_passwd); // did the bind succeed? if ($bind) { ldap_close($conn); return array('handle' => $this->_handle); } else { $this->_err = @ldap_errno($conn) . " " . @ldap_error($conn); ldap_close($conn); return false; } }
public static function get_connection() { if (!ADLdap::$conn) { // ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); ADLdap::$conn = ldap_connect("ldap://" . getenv('LDAP_HOST')); if (!ADLdap::$conn) { error_log(ldap_error(ADLdap::$conn)); return null; } else { $adUserName = getenv('LDAP_USER'); $adPassword = getenv('LDAP_PASSWORD'); $adDomain = getenv('LDAP_DOMAIN'); ldap_set_option(ADLdap::$conn, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option(ADLdap::$conn, LDAP_OPT_NETWORK_TIMEOUT, 10); ldap_set_option(ADLdap::$conn, LDAP_OPT_REFERRALS, 0); ldap_set_option(ADLdap::$conn, LDAP_OPT_SIZELIMIT, 1000); //this is just for speed. if (!ldap_bind(ADLdap::$conn, $adUserName . "@" . $adDomain, $adPassword)) { echo ldap_error(ADLdap::$conn); die; return null; } } } return new ADLdap(); }
public function __construct($message, $ldapLink, $dn = null) { if ($ldapLink instanceof server) { $ldapLink = $ldapLink->getLink(); } parent::__construct(sprintf('LDAP exception (%s): %s (%s)', $dn ? $dn : 'global', $message, @ldap_error($ldapLink), @ldap_errno($ldapLink))); }
public static function updateProfile($numero_membre, $data) { $handle_ldap = self::initialize(); if (self::$isDisabled) { self::$logger->info("Ldap is disabled, doing nothing."); return false; } $membreExists = @ldap_search($handle_ldap, "cn={$numero_membre}, " . self::$conf['basedn'], "objectclass=*", array("cn", "description", "mail")); if ($membreExists) { $personnes = ldap_get_entries($handle_ldap, $membreExists); $personne = $personnes[0]; $dn = $personne["dn"]; //self::$logger->debug(print_r($personne, true)); $newEmail = self::$conf['defaultEmail']; if (isset($data['email']) && $data['email']) { $newEmail = $data['email']; } $hasLdapEmail = @is_array($personne["mail"]); $ldapData = ['mail' => [$newEmail]]; if ($hasLdapEmail) { self::$logger->info("Replacing ldap email for #{$numero_membre}: {$newEmail}"); ldap_mod_replace($handle_ldap, $dn, $ldapData); } else { self::$logger->info("Adding ldap email for #{$numero_membre}: {$newEmail}"); ldap_mod_add($handle_ldap, $dn, $ldapData); } $err = ldap_error($handle_ldap); if ($err != "Success") { return $err; } } else { return "Membre not found in ldap repo: #{$numero_membre}"; } }
function authenticate($username, $password) { global $config, $ds; if ($username && $ds) { // bind with sAMAccountName instead of full LDAP DN if (ldap_bind($ds, "{$username}@{$config['auth_ad_domain']}", $password)) { // group membership in one of the configured groups is required if (isset($config['auth_ad_require_groupmembership']) && $config['auth_ad_require_groupmembership'] > 0) { $search = ldap_search($ds, $config['auth_ad_base_dn'], "(samaccountname={$username})", array('memberOf')); $entries = ldap_get_entries($ds, $search); $user_authenticated = 0; foreach ($entries[0]['memberof'] as $entry) { $group_cn = get_cn($entry); if (isset($config['auth_ad_groups'][$group_cn]['level'])) { // user is in one of the defined groups $user_authenticated = 1; } } return $user_authenticated; } else { // group membership is not required and user is valid return 1; } } else { return 0; } } else { echo ldap_error($ds); } return 0; }
/** * @see ResultSet::getRecordCount() */ function getRecordCount() { $rows = @ldap_count_entries($this->result); if ($rows === null) { throw new SQLException("Error fetching num entries", ldap_error($this->conn->getResource())); } return (int) $rows; }
/** * Returns the first entry in the result set. * * @throws \gossi\ldap\LdapException If the read fails. * @return \gossi\ldap\LdapEntry The new LdapEntry. */ public function getFirstEntry() { $this->pointer = ldap_first_entry($this->conn, $this->result); if (ldap_errno($this->conn)) { throw new LdapException(ldap_error($this->conn), ldap_errno($this->conn)); } return new LdapEntry($this->conn, $this->pointer); }
/** * {@inheritdoc} */ public function bind($dn = null, $password = null) { if (!$this->connection) { $this->connect(); } if (false === @ldap_bind($this->connection, $dn, $password)) { throw new ConnectionException(ldap_error($this->connection)); } }
public function Logoff() { if (ldap_unbind($this->ldap_link)) { ZLog::Write(LOGLEVEL_INFO, sprintf("BackendLDAP->Logoff(): Disconnection successfull.")); } else { ZLog::Write(LOGLEVEL_INFO, sprintf("BackendLDAP->Logoff(): Disconnection failed. Error: %s", ldap_error($this->ldap_link))); } return true; }
public function get_info($val, $key = 'samaccountname') { $filter = $key . '=' . $val; $sr = @ldap_search($this->_conn, $this->_basedn, $filter); $info = ldap_get_entries($this->_conn, $sr); $error = ldap_error($this->_conn); if ($error && $error != 'Success') { throw new Exception($error); } return $info; }
public function connectToLDAP() { $this->ldap_link = ldap_connect(AUTH_SERVER, AUTH_PORT); if (!$this->ldap_link) { $this->msg = "Could not connect to the LDAP server (AUTH_SERVER)." . ldap_error($this->ldap_link); ldap_close($this->ldap_link); return false; } ldap_set_option($this->ldap_link, LDAP_OPT_PROTOCOL_VERSION, 3); return true; }
function existingUser($user) { global $activeDirectoryUser, $activeDirectoryPass; $this->_bind = @ldap_bind($this->_conn, "{$activeDirectoryUser}" . $this->_account_suffix, "{$activeDirectoryPass}"); $sr = ldap_search($this->_conn, $this->_base_dn, "samaccountname={$user}", array("samaccountname", "mail", "displayname")) or die(ldap_error($this->_conn)); $entries = ldap_get_entries($this->_conn, $sr); if (count($entries) > 0) { return array($entries[0]["displayname"][0], $entries[0]["mail"][0]); } else { return false; } }
public function __construct($message, $ldap = NULL) { if (is_resource($ldap)) { $error = ldap_error($ldap); if ($error) { parent::__construct($message . '. ' . $error, ldap_errno($ldap)); } else { parent::__construct($message); } } else { parent::__construct($message); } }
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))); } }
/** * Realiza la autentificacion utilizando un servidor LDAP * @return $value Retorna TRUE o FALSE de acuerdo al estado de la autentifiacion */ function autenticar($id_usuario, $clave, $datos_iniciales = null) { if (!extension_loaded('ldap')) { throw new toba_error("[Autenticación LDAP] no se encuentra habilitada la extensión LDAP"); } $conexion = @ldap_connect($this->server); ldap_set_option($conexion, LDAP_OPT_PROTOCOL_VERSION, 3); if (!$conexion) { toba::logger()->error('[Autenticación LDAP] No es posible conectarse con el servidor: ' . ldap_error($conexion)); return false; } //$bind = @ldap_bind($conexion); $bind = @ldap_bind($conexion, $this->bind_dn, $this->bind_pass); if (!$bind) { toba::logger()->error('[Autenticación LDAP] No es posible conectarse con el servidor: ' . ldap_error($conexion)); return false; } $res_id = @ldap_search($conexion, $this->dn, sprintf($this->filter, $id_usuario)); if (!$res_id) { toba::logger()->error('[Autenticación LDAP] Fallo búsqueda en el árbol: ' . ldap_error($conexion)); return false; } $cantidad = ldap_count_entries($conexion, $res_id); if ($cantidad == 0) { toba::logger()->error("[Autenticación LDAP] El usuario {$id_usuario} no tiene una entrada en el árbol"); return false; } if ($cantidad > 1) { toba::logger()->error("[Autenticación LDAP] El usuario {$id_usuario} tiene más de una entrada en el árbol"); return false; } $entrada_id = ldap_first_entry($conexion, $res_id); if ($entrada_id == false) { toba::logger()->error("[Autenticación LDAP] No puede obtenerse el resultado de la búsqueda" . ldap_error($conexion)); return false; } $usuario_dn = ldap_get_dn($conexion, $entrada_id); if ($usuario_dn == false) { toba::logger()->error("[Autenticación LDAP] No pude obtenerse el DN del usuario: " . ldap_error($conexion)); return false; } $link_id = @ldap_bind($conexion, $usuario_dn, $clave); if ($link_id == false) { toba::logger()->error("[Autenticación LDAP] Usuario/Contraseña incorrecta: " . ldap_error($conexion)); return false; } ldap_close($conexion); $usuario = $this->recuperar_usuario_toba($id_usuario); toba::logger()->debug("[Autenticación LDAP] OK"); return true; }
function ldapdie($ldap, $msg) { // http_response_code(500); $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; header("{$protocol} 500 Internal Server Error"); if ($ldap) { $err = ldap_error($ldap); @ldap_close($ldap); if ($err != "Success") { $msg = sprintf("%s: %s\n", $msg, $err); } } die($msg); }
public function search($filter, array $params = array(), $baseDn = null) { if (empty($baseDn)) { $baseDn = $this->baseDn(); } //Default params $params = array('scope' => 'sub', 'sizelimit' => 0, 'timelimit' => 0, 'attrsonly' => false, 'attributes' => array()) + $params; $result = ldap_search($this->conn, $baseDn, $filter, $params['attributes'], $params['attrsonly'], $params['sizelimit'], $params['timelimit']); if ($result === false) { throw new RuntimeException('Failed to search in the LDAP tree : ' . ldap_error($this->conn)); } $data = ldap_get_entries($this->conn, $result); return $data; }
/** * * Fetch roles for a user. * * @param string $handle Username to get roles for. * * @return array An array of roles discovered in LDAP. * */ public function fetch($handle) { // connect $conn = @ldap_connect($this->_config['url']); // did the connection work? if (!$conn) { throw $this->_exception('ERR_CONNECTION_FAILED', array('url' => $this->_config['url'])); } // upgrade to LDAP3 when possible @ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3); // bind to the server if ($this->_config['binddn']) { // authenticated bind $bind = @ldap_bind($conn, $this->_config['binddn'], $this->_config['bindpw']); } else { // anonumous bind $bind = @ldap_bind($conn); } // did we bind to the server? if (!$bind) { // not using $this->_exception() because we need fine control // over the error text throw Solar::exception(get_class($this), @ldap_errno($conn), @ldap_error($conn), array($this->_config)); } // search for the groups $filter = sprintf($this->_config['filter'], $handle); $attrib = (array) $this->_config['attrib']; $result = ldap_search($conn, $this->_config['basedn'], $filter, $attrib); // get the first entry from the search result and free the result. $entry = ldap_first_entry($conn, $result); ldap_free_result($result); // now get the data from the entry and close the connection. $data = ldap_get_attributes($conn, $entry); ldap_close($conn); // go through the attribute data and add to the list. only // retain numeric keys; the ldap entry will have some // associative keys that are metadata and not useful to us here. $list = array(); foreach ($attrib as $attr) { if (isset($data[$attr]) && is_array($data[$attr])) { foreach ($data[$attr] as $key => $val) { if (is_int($key)) { $list[] = $val; } } } } // done! return $list; }
public function identify($host, $dn, $pwd) { $ret = ''; $ds = ldap_connect($host); if ($ds) { ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_bind($ds, $dn, $pwd); $ret = ldap_error($ds); ldap_close($ds); } else { $ret = ldap_error($ds); } return $ret; }
/** * read binary attribute from one entry from the ldap directory * * @todo still needed??? * * @param string $_dn the dn to read * @param string $_filter search filter * @param array $_attribute which field to return * @return blob binary data of given field * @throws Exception with ldap error */ public function fetchBinaryAttribute($_dn, $_filter, $_attribute) { $searchResult = @ldap_search($this->getResource(), $_dn, $_filter, $_attributes, $this->_attrsOnly, $this->_sizeLimit, $this->_timeLimit); if ($searchResult === FALSE) { throw new Exception(ldap_error($this->getResource())); } $searchCount = ldap_count_entries($this->getResource(), $searchResult); if ($searchCount === 0) { throw new Exception('Nothing found for filter: ' . $_filter); } elseif ($searchCount > 1) { throw new Exception('More than one entry found for filter: ' . $_filter); } $entry = ldap_first_entry($this->getResource(), $searchResult); return ldap_get_values_len($this->getResource(), $entry, $attribute); }
private function connect() { if ($this->connection) { return; } $host = $this->config['host']; ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, $this->config['version']); ldap_set_option($this->connection, LDAP_OPT_REFERRALS, $this->config['optReferrals']); $this->connection = ldap_connect($host, $this->config['port']); if (false === $this->connection) { throw new LdapException(sprintf('Could not connect to Ldap server: %s', ldap_error($this->connection))); } if ($this->config['useStartTls'] && false === ldap_start_tls($this->connection)) { throw new LdapException(sprintf('Could not initiate TLS connection: %s', ldap_error($this->connection))); } }