private static function readFromLdapEntry($ldapconn, $entry) { $newUser = new User(); $newUser->dn = ldap_get_dn($ldapconn, $entry); // Load attributes $att = ldap_get_attributes($ldapconn, $entry); if (isset($att['cn']) && $att['cn']['count'] == 1) { $newUser->cn = $att['cn'][0]; } if (isset($att['mail']) && $att['mail']['count'] == 1) { $newUser->mail = $att['mail'][0]; } if (isset($att['displayName']) && $att['displayName']['count'] == 1) { $newUser->displayName = $att['displayName'][0]; } if (isset($att['sn']) && $att['sn']['count'] == 1) { $newUser->sn = $att['sn'][0]; } if (isset($att['givenName']) && $att['givenName']['count'] == 1) { $newUser->givenName = $att['givenName'][0]; } $groups = []; if (isset($att['memberOf'])) { for ($i = 0; $i < $att['memberOf']['count']; $i++) { $groups[] = $att['memberOf'][$i]; } } $newUser->group_dns = $groups; $newUser->ldapconn = $ldapconn; return $newUser; }
public function add_login($ad, $grupo, $user, $bdn, $ous) { try { $ous = "CN=" . $grupo . "," . $ous; if (self::login($ad, "*****@*****.**", "Ac9a7533#Ed")) { ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($ad, LDAP_OPT_REFERRALS, 0); $results = ldap_search($ad, $bdn, "(sAMAccountName={$user})", array("sn", "cn"), 0, 1); $entry = ldap_get_entries($ad, $results); $first = ldap_first_entry($ad, $results); $dn = ldap_get_dn($ad, $first); $data = $entry[0]['cn'][0]; //$dn = str_replace($data, $user, $dn); //echo $dn; $user_array['member'] = $dn; //echo $ous; if (ldap_mod_add($ad, $ous, $user_array)) { return 1; } else { return 0; } //end if*/ } else { return 0; } //end if } catch (Exception $e) { return 0; } //end try }
/** * @return mixed resource */ public function fetchEntry() { if (!$this->result_resource) { return null; } if (null === $this->entry_resource) { $this->entry_resource = ldap_first_entry($this->resource, $this->result_resource); } else { $this->entry_resource = ldap_next_entry($this->resource, $this->entry_resource); } if (!$this->entry_resource) { return null; } $dn = ldap_get_dn($this->resource, $this->entry_resource); $rawAttributes = ldap_get_attributes($this->resource, $this->entry_resource); $count = $rawAttributes['count']; $attributes = array(); for ($i = 0; $i < $count; $i++) { $attribute = $rawAttributes[$i]; $values = array(); $subCount = $rawAttributes[$attribute]['count']; for ($j = 0; $j < $subCount; $j++) { $values[] = $rawAttributes[$attribute][$j]; } $attributes[$attribute] = $values; } $object = new Object($dn, $attributes); return $object; }
function getUserDn($username) { if ($this->send_utf8_credentials) { $username = studip_utf8encode($username); $reader_password = studip_utf8encode($this->reader_password); } $user_dn = ""; if (!($r = @ldap_bind($this->conn, $this->reader_dn, $this->reader_password))) { $this->error_msg = sprintf(_("Anmeldung von %s fehlgeschlagen."), $this->reader_dn) . $this->getLdapError(); return false; } if (!($result = @ldap_search($this->conn, $this->base_dn, $this->getLdapFilter($username), array('dn')))) { $this->error_msg = _("Durchsuchen des LDAP Baumes fehlgeschlagen.") . $this->getLdapError(); return false; } if (!ldap_count_entries($this->conn, $result)) { $this->error_msg = sprintf(_("%s wurde nicht unterhalb von %s gefunden."), $username, $this->base_dn); return false; } if (!($entry = @ldap_first_entry($this->conn, $result))) { $this->error_msg = $this->getLdapError(); return false; } if (!($user_dn = @ldap_get_dn($this->conn, $entry))) { $this->error_msg = $this->getLdapError(); return false; } return $user_dn; }
/** * Authenticates a user to LDAP * * @param $username * @param $password * @param bool|false $returnUser * @return bool true if the username and/or password provided are valid * false if the username and/or password provided are invalid * array of ldap_attributes if $returnUser is true */ function ldap($username, $password, $returnUser = false) { $ldaphost = Setting::getSettings()->ldap_server; $ldaprdn = Setting::getSettings()->ldap_uname; $ldappass = Crypt::decrypt(Setting::getSettings()->ldap_pword); $baseDn = Setting::getSettings()->ldap_basedn; $filterQuery = Setting::getSettings()->ldap_auth_filter_query . $username; $ldapversion = Setting::getSettings()->ldap_version; // Connecting to LDAP $connection = ldap_connect($ldaphost) or die("Could not connect to {$ldaphost}"); // Needed for AD ldap_set_option($connection, LDAP_OPT_REFERRALS, 0); ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldapversion); try { if ($connection) { // binding to ldap server $ldapbind = ldap_bind($connection, $ldaprdn, $ldappass); if (($results = @ldap_search($connection, $baseDn, $filterQuery)) != false) { $entry = ldap_first_entry($connection, $results); if (($userDn = @ldap_get_dn($connection, $entry)) !== false) { if (($isBound = ldap_bind($connection, $userDn, $password)) == "true") { return $returnUser ? array_change_key_case(ldap_get_attributes($connection, $entry), CASE_LOWER) : true; } } } } } catch (Exception $e) { LOG::error($e->getMessage()); } ldap_close($connection); return false; }
/** * Authenticates a user to LDAP * * @return true if the username and/or password provided are valid * false if the username and/or password provided are invalid * */ function ldap($username, $password) { $ldaphost = Config::get('ldap.url'); $ldaprdn = Config::get('ldap.username'); $ldappass = Config::get('ldap.password'); $baseDn = Config::get('ldap.basedn'); $filterQuery = Config::get('ldap.authentication.filter.query') . $username; // Connecting to LDAP $connection = ldap_connect($ldaphost) or die("Could not connect to {$ldaphost}"); // Needed for AD ldap_set_option($connection, LDAP_OPT_REFERRALS, 0); try { if ($connection) { // binding to ldap server $ldapbind = ldap_bind($connection, $ldaprdn, $ldappass); if (($results = @ldap_search($connection, $baseDn, $filterQuery)) !== false) { $entry = ldap_first_entry($connection, $results); if (($userDn = @ldap_get_dn($connection, $entry)) !== false) { if (($isBound = ldap_bind($connection, $userDn, $password)) == "true") { return true; } } } } } catch (Exception $e) { LOG::error($e->getMessage()); } ldap_close($connection); return false; }
function checkldapuser($username, $password) { require 'config.php'; $username = strtolower($username); $connect = ldap_connect($ldapServer); if ($connect != false) { ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($connect, LDAP_OPT_REFERRALS, 0); // enlace a la conexión $bind = ldap_bind($connect, $usrLDAP, $pwdLDAP); if ($bind == false) { $mensajeError = "Falla la conexión con el servidor LDAP con el usuario \n{$usrLDAP}"; return $mensajeError; } // active directory - pch $bind = @ldap_bind($connect, "{$campoBusqLDAP}=" . $username . ",{$cadenaBusqLDAP}", $password); if ($bind == false) { $mensajeError = "Usuario o contraseña incorrecta"; return $mensajeError; } // busca el usuario - pch if (($res_id = ldap_search($connect, $cadenaBusqLDAP, "{$campoBusqLDAP}=" . $username)) == false) { $mensajeError = "No encontrado el usuario en el LDAP"; return $mensajeError; } $cant = ldap_count_entries($connect, $res_id); if ($cant == 0) { $mensajeError = "El usuario {$username} NO se encuentra en el A.D. {$bind} HLPHLP"; return $mensajeError; } if ($cant > 1) { $mensajeError = "El usuario {$username} se encuentra {$cant} veces en el A.D."; return $mensajeError; } $entry_id = ldap_first_entry($connect, $res_id); if ($entry_id == false) { $mensajeError = "No se obtuvieron resultados"; return $mensajeError; } if (($user_dn = ldap_get_dn($connect, $entry_id)) == false) { $mensajeError = "No se puede obtener el dn del usuario"; return $mensajeError; } error_reporting(0); /* Autentica el usuario */ if (($link_id = ldap_bind($connect, "{$user_dn}", $password)) == false) { error_reporting(0); $mensajeError = "USUARIO O CONTRASEÑA INCORRECTOS"; return $mensajeError; } return ''; @ldap_close($connect); } else { $mensajeError = "no hay conexión a '{$ldap_server}'"; return $mensajeError; } @ldap_close($connect); return false; }
private function setEntry($entry) { if ($entry) { $this->_current_entry = $entry; $row = ldap_get_attributes($this->_link, $entry); $row["dn"] = ldap_get_dn($this->_link, $entry); return $row; } }
function login($uid, $pwd, $ip = 0) { // connect to ldap-server // echo ("Host: ".$this->host." Port: ".$this->port." BaseDN: ".$this->basedn." UID: $uid, PWD: $pwd \n<br>\n"); if ($connect = @ldap_connect($this->host)) { // if connected to ldap server, check for protocol version if (!@ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3)) { // echo "version 2<br>\n"; $this->ldapver = 2; } // echo "verification on '$this->host': "; // bind to ldap connection if (($bind = @ldap_bind($connect)) == false) { // print "bind:__FAILED__<br>\n"; return false; } // check whether we have an email address or an actual user id if (strpos($uid, '@') > 0) { $filter = "mail=" . $uid; } else { $filter = "uid=" . $uid; } // search for user if (($res_id = @ldap_search($connect, $this->basedn, $filter)) == false) { // print "failure: search in LDAP-tree failed<br>"; return false; } if (@ldap_count_entries($connect, $res_id) != 1) { // print "failure: error looking up user $username<br>\n"; return false; } if (($entry_id = @ldap_first_entry($connect, $res_id)) == false) { // print "failure: entry of searchresult couln't be fetched<br>\n"; return false; } if (($user_dn = @ldap_get_dn($connect, $entry_id)) == false) { // print "failure: user-dn coulnd't be fetched<br>\n"; return false; } // authenticate user if (($link_id = @ldap_bind($connect, $user_dn, $pwd)) == false) { // print "failure: username, password didn't match: $user_dn<br>\n"; return false; } // login went fine, user login is ok @ldap_close($connect); $this->uid = $uid; return true; } else { // no conection to ldap server echo "no connection to '{$ldap_server}'<br>\n"; } // echo "failed: ".ldap_error($connect)."<BR>\n"; // something went wrong, cleanup and return false @ldap_close($connect); return false; }
function ldapauth_authenticate($username, $password) { $ldap_server = get_config('ldapauth', 'ldap_server'); $ldap_binddn = get_config('ldapauth', 'ldap_binddn'); $ldap_bindpw = get_config('ldapauth', 'ldap_bindpw'); $ldap_searchdn = get_config('ldapauth', 'ldap_searchdn'); $ldap_userattr = get_config('ldapauth', 'ldap_userattr'); $ldap_group = get_config('ldapauth', 'ldap_group'); if (!(strlen($password) && function_exists('ldap_connect') && strlen($ldap_server))) { return false; } $connect = @ldap_connect($ldap_server); if (!$connect) { return false; } @ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3); @ldap_set_option($connect, LDAP_OPT_REFERRALS, 0); if (@ldap_bind($connect, $ldap_binddn, $ldap_bindpw) === false) { return false; } $res = @ldap_search($connect, $ldap_searchdn, $ldap_userattr . '=' . $username); if (!$res) { return false; } $id = @ldap_first_entry($connect, $res); if (!$id) { return false; } $dn = @ldap_get_dn($connect, $id); if (!@ldap_bind($connect, $dn, $password)) { return false; } if (!strlen($ldap_group)) { return true; } $r = @ldap_compare($connect, $ldap_group, 'member', $dn); if ($r === -1) { $err = @ldap_error($connect); $eno = @ldap_errno($connect); @ldap_close($connect); if ($eno === 32) { logger("ldapauth: access control group Does Not Exist"); return false; } elseif ($eno === 16) { logger('ldapauth: membership attribute does not exist in access control group'); return false; } else { logger('ldapauth: error: ' . $err); return false; } } elseif ($r === false) { @ldap_close($connect); return false; } return true; }
/** * Fetches the current entry. * * @return Entry */ public function current() { $attributes = ldap_get_attributes($this->connection, $this->current); if (false === $attributes) { throw new LdapException(sprintf('Could not fetch attributes: %s', ldap_error($this->connection))); } $dn = ldap_get_dn($this->connection, $this->current); if (false === $dn) { throw new LdapException(sprintf('Could not fetch DN: %s', ldap_error($this->connection))); } return new Entry($dn, $attributes); }
/** * 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; }
/** * LDAPEngine constructor to initialize object * @param string $uid user id * @param string $password password associated with uid */ function LDAPEngine($uid, $password) { global $conf; $this->connected = false; if (strlen($uid) == 0 || strlen($password) == 0) { return; } $this->host = $conf['ldap']['host']; $this->port = $conf['ldap']['port']; $this->basedn = $conf['ldap']['basedn']; $this->AD_lookupid = $conf['ldap']['lookupid']; $this->AD_lookuppwd = $conf['ldap']['lookuppwd']; $this->ldap = ldap_connect($this->host, $this->port) or die("Could not connect to LDAP server."); $this->uid = $uid; if ($this->ldap) { $bind = $this->AD_lookupid ? @ldap_bind($this->ldap, $this->AD_lookupid, $this->AD_lookuppwd) : @ldap_bind($this->ldap); if ($bind) { // System authentication was a success, lookup user's dn via uid= filter $result = ldap_search($this->ldap, $this->basedn, "uid" . "=" . $this->uid); if (ldap_count_entries($this->ldap, $result) <= 0) { print "<p>LDAPEngine: Search in LDAP failed. uid={$this->uid}<p>"; ldap_close($this->ldap); return; } else { $this->binddn = ldap_get_dn($this->ldap, ldap_first_entry($this->ldap, $result)); //print "<p>LDAPEngine: User binding as dn=".$this->binddn."<p>"; $bind2 = @ldap_bind($this->ldap, $this->binddn, $password); if ($bind2) { //print "<p>LDAPEngine: bind using user credentials successful.</p>"; } else { //print "<p>LDAPEngine: bind using user credentials failed.</p>"; ldap_close($this->ldap); return; } } // ------------------------------------ if ($this->loadUserData()) { $this->connected = true; $this->password = $password; } else { ldap_close($this->ldap); } } else { die("LDAPEngine: Attempt to bind to:" . $this->host . " using systemid:" . $this->lookupid . " failed."); ldap_close($this->ldap); } } }
/** * Auxiliar directo de ldapAccess::iterarEntradas * Configura el valor de cada atributos en $atributos de $entrada * @param array $atributos * @param ldap result entry $entrada * @return type */ private function mapa(array $atributos, $entrada) { $objeto = array('dn' => ldap_get_dn($this->conexionLdap, $entrada)); foreach ($atributos as $attr) { if ($valor = @ldap_get_values($this->conexionLdap, $entrada, $attr)) { // Elimino el índice count array_pop($valor); // $valor es un array. // En caso de ser valor único, tomamos el indíce cero, caso contrario // metemos todo el array $objeto[$attr] = count($valor) == 1 ? $valor[0] : $valor; } // TODO: ¿Un else para configurar un valor por defecto } return $objeto; }
function bh_authenticate($username, $password) { global $bhconfig; // first, verify that the user is allowed to use this application // look for the user in the user table $authrows = select_bhdb("users", array('username' => $username), 1); if (empty($authrows)) { return 0; } elseif ($authrows[0]['disabled'] == 1) { return -1; } // now check against LDAP $port = $bhconfig['ldapport'] ? $bhconfig['ldapport'] : 389; // Connect to LDAP server $ds = @ldap_connect($bhconfig['ldapsrv'], $port); if ($ds) { // Bind as anonymous $r = @ldap_bind($ds); // find user entry in the tree $sr = @ldap_search($ds, $bhconfig['ldapbase'], $bhconfig['ldapattr'] . "={$username}"); // Must find one entry, no more no less if (@ldap_count_entries($ds, $sr) != 1) { // user unknown @ldap_close($ds); return false; } // find entry in the result set if (($entry = @ldap_first_entry($ds, $sr)) == false) { // user unknown @ldap_close($ds); return 0; } // bind as the user to verify pasword $dn = ldap_get_dn($ds, $entry); $r = @ldap_bind($ds, $dn, $password); // Link no longer needed @ldap_close($ds); if ($r) { return true; } else { return false; } } else { return false; } }
/** * Get the next LDAP entry from search results. * * @return Entry|null * Next LDAP entry or null if no entries left. */ public function next() { if ($this->entryID === null) { $this->entryID = ldap_first_entry($this->ds, $this->sr); } else { $this->entryID = ldap_next_entry($this->ds, $this->entryID); } if (!$this->entryID) { return null; } $data = Utils::readEntry($this->ds, $this->entryID, $this->binaryFields); if (array_key_exists('nsRole', $data)) { $data['roles'] = Utils::getRoles($this->ds, $data); } $dn = ldap_get_dn($this->ds, $this->entryID); $rdn = Utils::getRDN($dn, $this->baseDN); return new Entry($this->ds, $rdn, $dn, $data); }
/** */ protected function _changePassword($user, $oldpass, $newpass) { global $conf; // Connect to the LDAP server. $ds = ldap_connect($conf['kolab']['ldap']['server'], $conf['kolab']['ldap']['port']); if (!$ds) { throw new Passwd_Exception(_("Could not connect to LDAP server")); } ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // Bind anonymously, or use the phpdn user if available. if (!empty($conf['kolab']['ldap']['phpdn'])) { $phpdn = $conf['kolab']['ldap']['phpdn']; $phppw = $conf['kolab']['ldap']['phppw']; $result = @ldap_bind($ds, $phpdn, $phppw); } else { $result = @ldap_bind($ds); } if (!$result) { throw new Passwd_Exception(_("Could not bind to LDAP server")); } // Make sure we're using the full user@domain format. if (strstr($user, '@') === false) { $user .= '@' . $conf['kolab']['imap']['maildomain']; } // Find the user's DN. $result = ldap_search($ds, $conf['kolab']['ldap']['basedn'], 'mail=' . $user); $entry = ldap_first_entry($ds, $result); if ($entry === false) { throw new Passwd_Exception(_("User not found.")); } $userdn = ldap_get_dn($ds, $entry); // Connect as the user. $result = @ldap_bind($ds, $userdn, $old_password); if (!$result) { throw new Passwd_Exception(_("Incorrect old password.")); } // And finally change the password. $new_details['userPassword'] = '******' . base64_encode(pack('H*', sha1($newpass))); if (!ldap_mod_replace($ds, $userdn, $new_details)) { throw new Passwd_Exception(ldap_error($ds)); } ldap_unbind($ds); }
protected function realLogin($user, $pass) { if (!preg_match(REGEX_EMAIL, $user)) { throw new Exception('Validation failed: Username is not an email', -8); } $ldaphost = "ldaps://ldap.domain.tld"; $ldap_basedn = 'ou=ldap,o=domain.tld'; $ldap_filters = 'mail=' . $user; $ldap_attr = array('uid', 'mail'); // User validation if (!preg_match('/^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$/', $sUser)) { throw new Exception('Invalid email address', '-300'); } if ($ldapconn = ldap_connect($ldaphost)) { if (!ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 2)) { throw new Exception('ldap_set_option proto_version:' . ldap_error($ldapconn), -2); } // search for this email if ($sr = !ldap_search($ldapconn, $ldap_basedn, $ldap_filters, $ldap_attr)) { throw new Exception('ldap_search fail:' . ldap_error($ldapconn), -3); } if ($entry = !ldap_first_entry($ldapconn, $sr)) { throw new Exception('ldap_first_entry fail:' . ldap_error($ldapconn), -4); } // store some info to share with the environment if ($_SESSION['ldap_attributes'] = !ldap_attributes($ldapconn, $entry)) { throw new Exception('ldap_attributes:' . ldap_error($ldapconn), -5); } // retreive dn if ($user_dn = !ldap_get_dn($ldapconn, $entry)) { throw new Exception('ldap_get_dn fail:' . ldap_error($ldapconn), -6); } // test bind if (ldap_bind($ldapconn, $user_dn, $pass)) { ldap_unbind($ldapconn); } else { throw new Exception('ldap_bind:' . ldap_error($ldapconn), -7); } } else { throw new Exception('Could not connect to ' . $ldaphost . ' - ' . ldap_error($ldapconn), -1); } }
function checkldapuser($username, $password, $ldap_server) { if ($connect = @ldap_connect($ldap_server)) { // enlace a la conexión if (($bind = @ldap_bind($connect)) == false) { $mensajeError = "Falla la conexión con el servidor LDAP"; return $mensajeError; } // busca el usuario if (($res_id = ldap_search($connect, "ou=People, o=usuarios,o=superservicios.gov.co", "mail={$username}")) == false) { $mensajeError = "No encontrado el usuario en el árbol LDAP"; return $mensajeError; } if (ldap_count_entries($connect, $res_id) != 1) { $mensajeError = "El usuario {$username} se encontró mas de 1 vez"; return $mensajeError; } if (($entry_id = ldap_first_entry($connect, $res_id)) == false) { $mensajeError = "No se obtuvieron resultados"; return $mensajeError; } if (($user_dn = ldap_get_dn($connect, $entry_id)) == false) { $mensajeError = "No se puede obtener el dn del usuario"; return $mensajeError; } error_reporting(0); /* Autentica el usuario */ if (($link_id = ldap_bind($connect, $user_dn, $password)) == false) { error_reporting(0); $mensajeError = "USUARIO O CONTRASEÑA INCORRECTOS"; return $mensajeError; } return ''; @ldap_close($connect); } else { $mensajeError = "no hay conexión a '{$ldap_server}'"; return $mensajeError; } @ldap_close($connect); return false; }
protected function getUserLdapAttrs($mail) { $filter = "(&(phpgwAccountType=u)(mail=" . $mail . "))"; $ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn']; $justthese = array("dn", 'jpegPhoto', 'givenName', 'sn'); $ds = $this->getLdapCatalog()->ds; if ($ds) { $sr = @ldap_search($ds, $ldap_context, $filter, $justthese); if ($sr) { $entry = ldap_first_entry($ds, $sr); if ($entry) { $givenName = @ldap_get_values_len($ds, $entry, "givenname"); $sn = @ldap_get_values_len($ds, $entry, "sn"); $contactHasImagePicture = @ldap_get_values_len($ds, $entry, "jpegphoto") ? 1 : 0; $dn = ldap_get_dn($ds, $entry); return array("contactID" => urlencode($dn), "contactFirstName" => $givenName[0], "contactLastName" => $sn[0], "contactHasImagePicture" => $contactHasImagePicture); } } } return false; }
private function _searchUser($login, $filter = "") { global $conf; # Search for user if ($filter == "") { #$filter = "(&(objectClass=person)(" . $conf->auth_ldap->username_attr . "={search}))"; $filter = "(&" . $conf->auth_ldap->filter . "(" . $conf->auth_ldap->username_attr . "={search}))"; } $filter = str_replace("{search}", $login, $filter); #error_log($filter); $search = ldap_search($this->ldap, $conf->auth_ldap->base, $filter); error_log(print_r($search, true)); $errno = ldap_errno($this->ldap); if ($errno) { error_log("LDAP - Search error {$errno} (" . ldap_error($this->ldap) . ")"); return NULL; } else { # Get user DN $entry = ldap_first_entry($this->ldap, $search); error_log("Entry"); error_log(print_r($entry, true)); $userdn = ldap_get_dn($this->ldap, $entry); if (!$userdn) { error_log("LDAP - User " . $login . " not found"); return false; } else { $user_attrs = ldap_get_attributes($this->ldap, $entry); $user_attrs_cpy = array(); // XXX: Probably fine for most attributes we will use. foreach ($user_attrs as $key => $value) { $user_attrs_cpy[$key] = $value[0]; } $retval = array(); array_push($retval, $userdn); array_push($retval, $user_attrs_cpy); return $retval; } } return NULL; }
/** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(UserContract $user, array $credentials) { $email = $credentials['email']; $password = $credentials['password']; $ldap_conn = ldap_connect($this->ldapConfig['host'], $this->ldapConfig['port']); $ldap_bind = ldap_bind($ldap_conn, $this->ldapConfig['user'], $this->ldapConfig['password']); try { // Find By Email $escEmail = ldap_escape($email, '', LDAP_ESCAPE_FILTER); $filter = "(&(uid=*)(|(mail=" . $escEmail . ")" . "(gosaMailAlternateAddress=" . $escEmail . ")))"; $sr = ldap_search($ldap_conn, $this->ldapConfig['base'], $filter, []); if (!$sr) { return false; } $conn = ldap_connect($this->ldapConfig['host'], $this->ldapConfig['port']); $entry = ldap_first_entry($ldap_conn, $sr); while ($entry) { $dn = ldap_get_dn($ldap_conn, $entry); // Check Credentials // remove warnings for incorrect passwords $level = error_reporting(); error_reporting($level & ~E_WARNING); try { $bind = ldap_bind($conn, $dn, $password); if ($bind) { // successful ldap_unbind($conn); return true; } } finally { // restore warnings error_reporting($level); } $entry = ldap_next_entry($ldap_conn, $entry); } } finally { ldap_unbind($ldap_conn); } return false; }
function login($username, $password) { if (!$this->login || $this->username != $username) { $this->username = $username; $this->result_identifier = ldap_search($this->link_identifier, $this->ldap_dn, "(&(uid=" . $this->username . ")" . $this->ldap_filter . ")", array("uid", "givenName", "sn")); if (!$this->result_identifier) { return false; } if (ldap_count_entries($this->link_identifier, $this->result_identifier) != 1) { return false; } $this->result_entry_identifier = ldap_first_entry($this->link_identifier, $this->result_identifier); if (!$this->result_entry_identifier) { return false; } $this->bind_rdn = ldap_get_dn($this->link_identifier, $this->result_entry_identifier); if (!@ldap_bind($this->link_identifier, $this->bind_rdn, $password)) { return false; } } $this->login = true; return true; }
function bh_authenticate($username, $password) { global $bhconfig; $port = $bhconfig['ldapport'] ? $bhconfig['ldapport'] : 389; // Connect to LDAP server $ds = @ldap_connect($bhconfig['ldapsrv'], $port); if ($ds) { // Bind as anonymous $r = @ldap_bind($ds); // find user entry in the tree $sr = @ldap_search($ds, $bhconfig['ldapbase'], $bhconfig['ldapattr'] . "={$username}"); // Must find one entry, no more no less if (@ldap_count_entries($ds, $sr) != 1) { // user unknown @ldap_close($ds); return 0; } // find entry in the result set if (($entry = @ldap_first_entry($ds, $sr)) == false) { // user unknown @ldap_close($ds); return 0; } // bind as the user to verify pasword $dn = ldap_get_dn($ds, $entry); $r = @ldap_bind($ds, $dn, $password); // Link no longer needed @ldap_close($ds); if ($r) { return 1; } else { return 0; } } else { return 0; } }
/** * LDAP Connection class for Monash Directory Services */ public function authenticate($username, $password) { if ($username != null && $username != '' && $password != null && $password != '') { $ldapcon = @ldap_connect(MONASH_DIR); if ($ldapcon) { $ldapsearch = @ldap_search($ldapcon, MONASH_FILTER, "uid=" . $username); if ($ldapsearch) { $ldapinfo = @ldap_first_entry($ldapcon, $ldapsearch); if ($ldapinfo) { $ldapresult = @ldap_bind($ldapcon, ldap_get_dn($ldapcon, $ldapinfo), $password); return $ldapresult; } else { return false; } } else { return false; } } else { return false; } } else { return false; } }
function get_ldap($uid, $pw) { // After connecting, you have to set the version to 3. $ldap = ldap_connect('geniusroom.local'); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); // Searches based on the entered username and then stores the user info. // This works best if the UID passed is "cleaned" via the function above. $search = ldap_search($ldap, 'cn=users,dc=geniusroom,dc=local', 'uid=' . clean_text($uid)); $info = ldap_get_entries($ldap, $search); // In order to bind properly, the "distinguished name" (DN) is needed. // This gets the DN and then tries to bind with the supplied password. // Getting the DN is redundant in *most* cases, but not all. $person = ldap_first_entry($ldap, $search); $dn = ldap_get_dn($ldap, $person); $bind = ldap_bind($ldap, $dn, $pw); // If the bind was successful, that means the user authenticated properly. // The "relative distinguished name" (CN) is the employee's proper name. // NOTE: The 'else' line below can be uncommented for guaranteed login. #if( $bind ) { return $info[0]['cn'][0]; } #else { return 'WYWO Developer'; } if ($bind) { return $info; } }
/** * Gets next entry * * @return peer.ldap.LDAPEntry or NULL if nothing was found * @throws peer.ldap.LDAPException in case of a read error */ public function next() { // If we have reached the number of results reported by ldap_count_entries() // - see constructor, return FALSE without trying to read further. Trying // to read "past the end" results in LDAP error #84 (decoding error) in some // client/server constellations, which is then incorrectly reported as an error. if ($this->iteration[1] >= $this->size) { return null; } // Fetch the next entry. Return FALSE if it was the last one (where really, // we shouldn't be getting here) $entry = ldap_next_entry($this->conn, $this->iteration[0]); if (!$entry) { if ($e = ldap_errno($this->conn)) { throw new LDAPException('Could not fetch next result entry.', $e); } return null; // EOF } // Keep track how many etnries we have fetched so we stop once we // have reached this number - see above for explanation. $this->iteration = [$entry, ++$this->iteration[1]]; return LDAPEntry::create(ldap_get_dn($this->conn, $entry), ldap_get_attributes($this->conn, $entry)); }
/** * Perform LDAP Authentication * * @access protected * @param string $username The username to validate * @param string $password The password to validate * @return bool */ protected function _perform_ldap_auth($username = '', $password = NULL) { if (empty($username)) { log_message('debug', 'LDAP Auth: failure, empty username'); return FALSE; } log_message('debug', 'LDAP Auth: Loading configuration'); $this->config->load('ldap.php', TRUE); $ldap = ['timeout' => $this->config->item('timeout', 'ldap'), 'host' => $this->config->item('server', 'ldap'), 'port' => $this->config->item('port', 'ldap'), 'rdn' => $this->config->item('binduser', 'ldap'), 'pass' => $this->config->item('bindpw', 'ldap'), 'basedn' => $this->config->item('basedn', 'ldap')]; log_message('debug', 'LDAP Auth: Connect to ' . (isset($ldaphost) ? $ldaphost : '[ldap not configured]')); // Connect to the ldap server $ldapconn = ldap_connect($ldap['host'], $ldap['port']); if ($ldapconn) { log_message('debug', 'Setting timeout to ' . $ldap['timeout'] . ' seconds'); ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, $ldap['timeout']); log_message('debug', 'LDAP Auth: Binding to ' . $ldap['host'] . ' with dn ' . $ldap['rdn']); // Binding to the ldap server $ldapbind = ldap_bind($ldapconn, $ldap['rdn'], $ldap['pass']); // Verify the binding if ($ldapbind === FALSE) { log_message('error', 'LDAP Auth: bind was unsuccessful'); return FALSE; } log_message('debug', 'LDAP Auth: bind successful'); } // Search for user if (($res_id = ldap_search($ldapconn, $ldap['basedn'], "uid={$username}")) === FALSE) { log_message('error', 'LDAP Auth: User ' . $username . ' not found in search'); return FALSE; } // Modified by Ivan Tcholakov, 10-JUL-2015. //if (ldap_count_entries($ldapconn, $res_id) !== 1) if (ldap_count_entries($ldapconn, $res_id) != 1) { log_message('error', 'LDAP Auth: Failure, username ' . $username . 'found more than once'); return FALSE; } if (($entry_id = ldap_first_entry($ldapconn, $res_id)) === FALSE) { log_message('error', 'LDAP Auth: Failure, entry of search result could not be fetched'); return FALSE; } if (($user_dn = ldap_get_dn($ldapconn, $entry_id)) === FALSE) { log_message('error', 'LDAP Auth: Failure, user-dn could not be fetched'); return FALSE; } // User found, could not authenticate as user if (($link_id = ldap_bind($ldapconn, $user_dn, $password)) === FALSE) { log_message('error', 'LDAP Auth: Failure, username/password did not match: ' . $user_dn); return FALSE; } log_message('debug', 'LDAP Auth: Success ' . $user_dn . ' authenticated successfully'); $this->_user_ldap_dn = $user_dn; ldap_close($ldapconn); return TRUE; }
/** * Retrieve the immediate children DNs of the given $parentDn * * This method is used in recursive methods like {@see delete()} * or {@see copy()} * * @param string|Zend_Ldap_Dn $parentDn * @return array of DNs */ protected function _getChildrenDns($parentDn) { if ($parentDn instanceof Zend_Ldap_Dn) { $parentDn = $parentDn->toString(); } $children = array(); $search = @ldap_list($this->getResource(), $parentDn, '(objectClass=*)', array('dn')); for ($entry = @ldap_first_entry($this->getResource(), $search); $entry !== false; $entry = @ldap_next_entry($this->getResource(), $entry)) { $childDn = @ldap_get_dn($this->getResource(), $entry); if ($childDn === false) { /** * @see Zend_Ldap_Exception */ #require_once 'Zend/Ldap/Exception.php'; throw new Zend_Ldap_Exception($this, 'getting dn'); } $children[] = $childDn; } @ldap_free_result($search); return $children; }
/** * Retrieve current user's scripts. * * @param resource $ldapcn The connection to the LDAP server. * @param string $userDN Set to the user object's real DN. * * @return array Script sources list. * @throws Ingo_Exception */ protected function _getScripts($ldapcn, &$userDN) { $attrs = array($this->_params['script_attribute'], 'dn'); $filter = $this->_substUser($this->_params['script_filter']); /* Find the user object. */ $sr = @ldap_search($ldapcn, $this->_params['script_base'], $filter, $attrs); if ($sr === false) { throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } if (@ldap_count_entries($ldapcn, $sr) != 1) { throw new Ingo_Exception(sprintf(_("Expected 1 object, got %d."), ldap_count_entries($ldapcn, $sr))); } $ent = @ldap_first_entry($ldapcn, $sr); if ($ent === false) { throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } /* Retrieve the user's DN. */ $v = @ldap_get_dn($ldapcn, $ent); if ($v === false) { @ldap_free_result($sr); throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } $userDN = $v; /* Retrieve the user's scripts. */ $attrs = @ldap_get_attributes($ldapcn, $ent); @ldap_free_result($sr); if ($attrs === false) { throw new Ingo_Exception(sprintf(_("Error retrieving current script: (%d) %s"), ldap_errno($ldapcn), ldap_error($ldapcn))); } /* Attribute can be in any case, and can have a ";binary" * specifier. */ $regexp = '/^' . preg_quote($this->_params['script_attribute'], '/') . '(?:;.*)?$/i'; unset($attrs['count']); foreach ($attrs as $name => $values) { if (preg_match($regexp, $name)) { unset($values['count']); return array_values($values); } } return array(); }