function ldap_authenticate($user, $pass)
{
    // Global variables
    global $ldap_base_DN, $ldap_server, $template, $admin_users, $ldap_user_cn;
    // Connect to the LDAP server
    $conn = ldap_connect($ldap_server) or die("Cannot connect");
    ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
    // Bind anonymously, query the server for the user, and error if it can't be found
    if (!($bind = ldap_bind($conn))) {
        $template['message'] = "<p>Anonymous bind failed.</p>";
        return;
    }
    // Do a search for the username and get the DN - this is easier than manually constructing it
    if (!($search = ldap_search($conn, $ldap_base_DN, "{$ldap_user_cn}={$user}"))) {
        $template['message'] = "<p><strong>Error:</strong> Could not find the username.</p>";
        return;
    }
    // If there isn't only one row.
    if (ldap_count_entries($conn, $search) != 1) {
        $template['message'] = "<p>There was an error processing the username, or it cannot be found.</p>";
        return;
    }
    // Extract the entries, and bind with the user's full DN, then unset the password for security
    $entries = @ldap_get_entries($conn, $search);
    $bind_auth = @ldap_bind($conn, $entries[0]['dn'], $pass);
    unset($pass);
    // If we have a successful bind, add the relevant session information
    if ($bind_auth) {
        $_SESSION['admin'] = in_array($user, $admin_users);
        $_SESSION['username'] = $user;
        header('Location: index.php');
    } else {
        $template['message'] = "<p><strong>Login failed.</strong> Please try again.</p>";
    }
}
 /**
  * Get entries count
  */
 public function count()
 {
     if (!isset($this->count)) {
         $this->count = ldap_count_entries($this->conn, $this->ldap);
     }
     return $this->count;
 }
 function _encrypt($str_userpswd)
 {
     echo '&lt;h3>Prueba de consulta LDAP&lt;/h3>';
     echo 'Conectando ...';
     $ds = ldap_connect('localhost');
     echo 'El resultado de la conexi&oacute;n es ' . $ds . '&lt;p>';
     if ($ds) {
         echo 'Autentific&aacute;ndose  ...';
         $r = ldap_bind($ds);
         echo 'El resultado de la autentificaci&oacute;n es ' . $r . '&lt;p>';
         echo 'Buscando (sn=P*) ...';
         $sr = ldap_search($ds, 'o=halys, c=halys', 'sn=h*');
         echo 'El resultado de la b&uacute;squeda es ' . $sr . '&lt;p>';
         echo 'El n&uacute;mero de entradas devueltas es ' . ldap_count_entries($ds, $sr) . '&lt;p>';
         echo 'Recuperando entradas ...&lt;p>';
         $info = ldap_get_entries($ds, $sr);
         echo 'Devueltos datos de ' . $info['count'] . ' entradas:&lt;p>';
         for ($i = 0; $i < $info['count']; $i++) {
             echo 'dn es: ' . $info[$i]['dn'] . '&lt;br>';
             echo 'La primera entrada cn es: ' . $info[$i]['cn'][0] . '&lt;br>';
         }
         echo 'Cerrando conexi&oacute;n';
         ldap_close($ds);
     } else {
         echo '&lt;h4>Ha sido imposible conectar al servidor LDAP&lt;/h4>';
     }
 }
Example #4
0
 /**
  * Validate group membership
  *
  * Searches the LDAP server for group membership of the
  * supplied username.  Quotes all LDAP filter meta characters in
  * the user name before querying the LDAP server.
  *
  * @param  string Distinguished Name of the authenticated User
  * @return boolean
  */
 public function checkGroupMembership($user)
 {
     if (!is_resource($this->_resource)) {
         $this->connect();
     }
     $userDn = $this->_getAccountDn($user);
     foreach ($this->_options['groups'] as $group) {
         // make filter
         $filter = sprintf('(&(%s=%s)(%s=%s)%s)', $this->_options['groupAttr'], $group, $this->_options['memberAttr'], $this->_quoteFilterString($userDn), $this->_options['groupFilter']);
         // make search base dn
         $search_basedn = $this->_options['groupDn'];
         if ($search_basedn != '' && substr($search_basedn, -1) != ',') {
             $search_basedn .= ',';
         }
         $search_basedn .= $this->_options['baseDn'];
         $func_params = array($this->_resource, $search_basedn, $filter, array($this->_options['memberAttr']));
         $func_name = 'ldap_search';
         //echo "Searching with $func_name and filter $filter in $search_basedn";
         // search
         if (($result_id = @call_user_func_array($func_name, $func_params)) != false) {
             if (@ldap_count_entries($this->_resource, $result_id) == 1) {
                 @ldap_free_result($result_id);
                 //echo 'User is member of group';
                 return true;
             }
         }
     }
     // default
     throw new Zend_Ldap_Exception(null, 'User is NOT member of any group!', BDBLdap::LDAP_USER_NOT_MEMBER_OF_GROUP);
     return false;
 }
Example #5
0
 function DoTest($testname, $param, $hostname, $timeout, $params)
 {
     global $NATS;
     $url = $params[0];
     $bind = $params[1];
     $pasw = $params[2];
     $base = $params[3];
     $filter = $params[4];
     $ds = ldap_connect($url);
     if (!$ds) {
         return -2;
     }
     $ldap = $bind && $pasw ? ldap_bind($ds, $bind, $pasw) : ldap_bind($ds);
     if (!$ldap) {
         return -1;
     }
     if ($base && $filter) {
         $search = ldap_search($ds, $base, $filter);
         $val = ldap_count_entries($ds, $search);
     } else {
         $val = 1;
     }
     ldap_close($ds);
     return $val;
 }
Example #6
0
/**
 * Load current tags of an entry
 */
function ajax_loadtags($dn, $type = 'plain')
{
    global $conf;
    global $LDAP_CON;
    global $FIELDS;
    if (!$FIELDS['_marker']) {
        return;
    }
    header('Content-Type: text/html; charset=utf-8');
    $sr = ldap_search($LDAP_CON, $dn, '(objectClass=inetOrgPerson)', array($FIELDS['_marker']));
    if (!ldap_count_entries($LDAP_CON, $sr)) {
        return false;
    }
    $result = ldap_get_binentries($LDAP_CON, $sr);
    $entry = $result[0];
    if ($type == 'plain') {
        echo join(', ', (array) $entry[$FIELDS['_marker']]);
    } else {
        foreach ((array) $entry[$FIELDS['_marker']] as $tag) {
            echo '<a href="index.php?marker=';
            echo rawurlencode($tag);
            echo '" class="tag">';
            echo htmlspecialchars($tag);
            echo '</a> ';
        }
    }
}
Example #7
0
 public function count()
 {
     if (false !== ($count = ldap_count_entries($this->connection->getResource(), $this->search->getResource()))) {
         return $count;
     }
     throw new LdapException(sprintf('Error while retrieving entry count: %s', ldap_error($this->connection->getResource())));
 }
 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;
 }
Example #9
0
 /**
  * @return int
  * @throws EntryCountRetrievalFailureException
  */
 public function entryCount()
 {
     if (!($result = ldap_count_entries($this->link, $this->result))) {
         throw new EntryCountRetrievalFailureException(ldap_error($this->link), ldap_errno($this->link));
     }
     return $result;
 }
Example #10
0
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&oacute;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&Ntilde;A INCORRECTOS";
            return $mensajeError;
        }
        return '';
        @ldap_close($connect);
    } else {
        $mensajeError = "no hay conexi&oacute;n a '{$ldap_server}'";
        return $mensajeError;
    }
    @ldap_close($connect);
    return false;
}
 public function count_entries()
 {
     if (isset($this->search)) {
         return ldap_count_entries($this->ds, $this->search);
     } else {
         return 0;
     }
 }
Example #12
0
 public static function readUser($ldapconn, $dn)
 {
     $search = ldap_read($ldapconn, $dn, USER::FILTER_USERS, array("cn", "mail", "displayName", "sn", "givenName", "memberOf"));
     if (ldap_count_entries($ldapconn, $search) > 0) {
         $entry = ldap_first_entry($ldapconn, $search);
         return User::readFromLdapEntry($ldapconn, $entry);
     }
 }
 public function count_entries()
 {
     if (!empty($this->search)) {
         return ldap_count_entries($this->ds, $this->search);
     } else {
         throw new e_developer("Invalid count entries");
     }
 }
Example #14
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;
 }
Example #15
0
 /**
  *	LDAP storage handler
  *	@return bool
  *	@param $id string
  *	@param $pw string
  **/
 protected function _ldap($id, $pw)
 {
     $dc = @ldap_connect($this->args['dc']);
     if ($dc && ldap_set_option($dc, LDAP_OPT_PROTOCOL_VERSION, 3) && ldap_set_option($dc, LDAP_OPT_REFERRALS, 0) && ldap_bind($dc, $this->args['rdn'], $this->args['pw']) && ($result = ldap_search($dc, $this->args['base_dn'], 'uid=' . $id)) && ldap_count_entries($dc, $result) && ($info = ldap_get_entries($dc, $result)) && @ldap_bind($dc, $info[0]['dn'], $pw) && @ldap_close($dc)) {
         return $info[0]['uid'][0] == $id;
     }
     user_error(self::E_LDAP, E_USER_ERROR);
 }
Example #16
0
function ldap_mailhost_on_login($tools)
{
    // load the settings for this module
    require $tools->include_path . 'settings.php';
    // we're looking to find the user's imap server setting
    $imap_server = false;
    // user posted to login form
    if (isset($_POST['user'])) {
        $user = $_POST['user'];
        // check to see if the user specified their domain (user@domain)
        $domain = false;
        if (strstr($_POST['user'], '@') && strpos($_POST['user'], '@') < strlen($_POST['user'])) {
            $user = substr($_POST['user'], 0, strpos($_POST['user'], '@'));
            $domain = substr($_POST['user'], strpos($_POST['user'], '@') + 1);
        }
        // make sure we have safe input
        if (!preg_match($uid_pattern, $user)) {
            return;
        }
        if ($domain && !preg_match($domain_pattern, $domain)) {
            return;
        }
        // connect and bind to ldap
        if (!($connect = @ldap_connect($ldap_server))) {
            return;
        }
        if (!($bind = @ldap_bind($connect, $ldap_user, $ldap_pass))) {
            return;
        }
        // search for the user in the appropriate ldap base dn
        if (!($search = @ldap_search($connect, $domain ? sprintf($domain_base_format, $domain) : $default_base, sprintf($uid_filter_format, $user)))) {
            return;
        }
        // make sure we found one and only one user
        if (ldap_count_entries($connect, $search) != 1) {
            return;
        }
        // get the mailhost attribute from the user entry
        $info = ldap_get_entries($connect, $search);
        if ($info[0] && $info[0][$mailhost_attr] && $info[0][$mailhost_attr][0]) {
            $mailhost = $info[0][$mailhost_attr][0];
            // look up the mailhost value in the settings map to find
            // the corresponding imap_alt server
            foreach ($server_map as $alt_imap => $vals) {
                if ($mailhost == $vals) {
                    // if all went well
                    // we found the correct imap server to connect to
                    $_POST['imap_server'] = $alt_imap;
                    return;
                }
            }
        }
        // if something went wrong, the imap_server will remain whatever
        // the default imap_server setting is in hastymail.conf
        // depending on what that is set to, it will probably result in
        // and error to the user indicating that that imap server is down
    }
}
Example #17
0
 /**
  * Constructor.
  *
  * @param  \Zend\Ldap\Ldap $ldap
  * @param  resource  $resultId
  * @return void
  */
 public function __construct(Ldap\Ldap $ldap, $resultId)
 {
     $this->_ldap = $ldap;
     $this->_resultId = $resultId;
     $this->_itemCount = @ldap_count_entries($ldap->getResource(), $resultId);
     if ($this->_itemCount === false) {
         throw new Ldap\Exception($this->_ldap, 'counting entries');
     }
 }
 public function search($statement)
 {
     //returns false if there is a problem
     $results = array();
     $_search = ldap_search($this->_ldapCnx, $this->_baseDn, $statement, $this->_resultFields);
     $results['data'] = ldap_get_entries($this->_ldapCnx, $_search);
     $results['count'] = ldap_count_entries($this->_ldapCnx, $_search);
     return $results;
 }
 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;
 }
Example #20
0
 public function doSearch($filter)
 {
     $numEntries = 0;
     if (!$this->bindResult) {
         $this->connect();
     }
     @($this->searchResult = ldap_search($this->ldapConnection, $this->baseDN, $filter, $this->ldapAttributes));
     @($this->numEntries = ldap_count_entries($this->ldapConnection, $this->searchResult));
     return $this->numEntries;
 }
 /**
  * getGroupMembership() - return any group names the user is a member of; including those that are not relevant for yacy collections
  * filtering/mapping is done in class UserPrivs, 
  * @see class/user_privs.class.php
  * 
  * @return array list of all found group names
  */
 public static function getGroupMemberShip()
 {
     // try to connect to one of the given ldap/ad server
     $ldapConnect = false;
     foreach (Config::$ldapServer as $ldapHost) {
         if (!$ldapConnect) {
             $ldapConnect = ldap_connect($ldapHost);
         }
     }
     if ($ldapConnect) {
         ldap_set_option($ldapConnect, LDAP_OPT_PROTOCOL_VERSION, 3);
         ldap_set_option($ldapConnect, LDAP_OPT_REFERRALS, 0);
         // ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 1); // debug only
         // bind with the given system account to determine user's distinguished name (dn)
         $ldapBind = ldap_bind($ldapConnect, Config::BIND_DN, Config::BIND_PASSWORD);
         if ($ldapBind) {
             if (Config::DEBUG) {
                 trigger_error('ldap bind with system credentials: success', E_USER_NOTICE);
                 trigger_error('trying to authenticate user: '******'dn'];
                 if (Config::DEBUG) {
                     trigger_error('found user dn: ' . $userDN, E_USER_NOTICE);
                 }
                 // re-bind with user-specific credentials (determined dn and given pass)
                 $ldapBind = ldap_bind($ldapConnect, $userDN, self::AUTH_PWD);
                 if ($ldapBind) {
                     if (Config::DEBUG) {
                         trigger_error('bind with user specific credentials: success', E_USER_NOTICE);
                     }
                     $commonName = $ldapRecords[0]['cn'][0];
                     $ldapSearchQuery = 'CN=' . $commonName;
                     $ldapResult = ldap_search($ldapConnect, Config::LDAP_BASE_DN, $ldapSearchQuery);
                     $ldapRecords = ldap_get_entries($ldapConnect, $ldapResult);
                     $isMemberOf = array();
                     for ($i = 0; $i < $ldapRecords[0]['memberof']['count']; $i++) {
                         $isMemberOf[] = $ldapRecords[0]['memberof'][$i];
                     }
                     return $isMemberOf;
                 } else {
                     throw new Exception('received exactly one dn, but could not bind - please check the given credentials');
                 }
             } else {
                 throw new Exception('could not determine users dn - please verify the given credentials');
             }
         } else {
             throw new Exception('could not bind with system account - please verify the system account given');
         }
     } else {
         throw new Exception('could not connect to any of the given ldap/ad server');
     }
 }
Example #22
0
 /**
  * Constructor.
  *
  * @param  \Zend\Ldap\Ldap $ldap
  * @param  resource        $resultId
  * @throws \Zend\Ldap\Exception\LdapException if no entries was found.
  * @return DefaultIterator
  */
 public function __construct(Ldap\Ldap $ldap, $resultId)
 {
     $this->ldap = $ldap;
     $this->resultId = $resultId;
     ErrorHandler::start();
     $this->itemCount = ldap_count_entries($ldap->getResource(), $resultId);
     ErrorHandler::stop();
     if ($this->itemCount === false) {
         throw new Exception\LdapException($this->ldap, 'counting entries');
     }
 }
Example #23
0
 /**
  * Loads an entry from the LDAP server for the given user
  *
  * @param array $config
  * @param string $username
  */
 public function __construct($username)
 {
     $config = self::getConfig();
     $this->openConnection();
     $result = ldap_search(self::$connection, $config['DIRECTORY_BASE_DN'], $config['DIRECTORY_USERNAME_ATTRIBUTE'] . "={$username}");
     if (ldap_count_entries(self::$connection, $result)) {
         $entries = ldap_get_entries(self::$connection, $result);
         $this->entry = $entries[0];
     } else {
         throw new \Exception('ldap/unknownUser');
     }
 }
Example #24
0
 public function search($username)
 {
     if ($ds = $this->baseConnect()) {
         $base = $this->base_schema . ',' . $this->base;
         $filter = "({$this->directoryString}={$username})";
         $sr = ldap_search($ds, $base, $filter);
         $info = ldap_count_entries($ds, $sr);
         ldap_close($ds);
         return $info;
     }
     return null;
 }
Example #25
0
 /**
  * Constructor.
  *
  * @param  Zend_Ldap $ldap
  * @param  resource  $resultId
  * @return void
  */
 public function __construct(Zend_Ldap $ldap, $resultId)
 {
     $this->_ldap = $ldap;
     $this->_resultId = $resultId;
     $this->_itemCount = @ldap_count_entries($ldap->getResource(), $resultId);
     if ($this->_itemCount === false) {
         /**
          * @see Zend_Ldap_Exception
          */
         require_once 'Zend/Ldap/Exception.php';
         throw new Zend_Ldap_Exception($this->_ldap, 'counting entries');
     }
 }
Example #26
0
 /**
  *	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;
 }
 /**
  * Authenticates a user against ldap server.
  * @return boolean whether authentication succeeds.
  */
 public function authenticate()
 {
     try {
         $serverType = Yii::app()->authenticationHelper->ldapServerType;
         $host = Yii::app()->authenticationHelper->ldapHost;
         $port = Yii::app()->authenticationHelper->ldapPort;
         $baseDomain = Yii::app()->authenticationHelper->ldapBaseDomain;
         $bindPassword = Yii::app()->authenticationHelper->ldapBindPassword;
         $bindRegisteredDomain = Yii::app()->authenticationHelper->ldapBindRegisteredDomain;
         $ldapConnection = LdapUtil::establishConnection($serverType, $host, $port, $bindRegisteredDomain, $bindPassword, $baseDomain);
         if ($ldapConnection) {
             if ($serverType == ZurmoAuthenticationHelper::SERVER_TYPE_OPEN_LDAP) {
                 $ldapFilter = '(|(cn=' . $this->username . ')(&(uid=' . $this->username . ')))';
             } elseif ($serverType == ZurmoAuthenticationHelper::SERVER_TYPE_ACTIVE_DIRECTORY) {
                 $ldapFilter = '(sAMAccountName=' . $this->username . ')';
             } else {
                 throw new NotSupportedException();
             }
             $ldapResults = ldap_search($ldapConnection, $baseDomain, $ldapFilter);
             $ldapResultsCount = ldap_count_entries($ldapConnection, $ldapResults);
             if ($ldapResultsCount > 0) {
                 $result = @ldap_get_entries($ldapConnection, $ldapResults);
                 $zurmoLogin = parent::authenticate();
                 if (!$zurmoLogin) {
                     if ($result[0] && @ldap_bind($ldapConnection, $result[0]['dn'], $this->password)) {
                         if ($this->errorCode != 1) {
                             $this->setState('username', $this->username);
                             $this->errorCode = self::ERROR_NONE;
                             return true;
                         }
                     }
                 } else {
                     $this->setState('username', $this->username);
                     $this->errorCode = self::ERROR_NONE;
                     return true;
                 }
             } else {
                 return parent::authenticate();
             }
         } else {
             return parent::authenticate();
         }
     } catch (NotFoundException $e) {
         $this->errorCode = self::ERROR_USERNAME_INVALID;
     } catch (BadPasswordException $e) {
         $this->errorCode = self::ERROR_PASSWORD_INVALID;
     } catch (NoRightWebLoginException $e) {
         $this->errorCode = self::ERROR_NO_RIGHT_WEB_LOGIN;
     }
     return false;
 }
 function auth($user, $pass, $args)
 {
     if ($this->ldapless_php) {
         return false;
     } else {
         if ($ldsrvs = access_query("authldapserver")) {
             foreach ($ldsrvs as $ld_srv) {
                 if ($ld_cid = ldap_connect($ld_srv)) {
                     break;
                 }
             }
             if (!$ld_cid) {
                 techo("WARN: mod_auth_ldap: unable to connect to server(s)", NW_EL_WARNING);
                 return false;
             }
         } else {
             techo("WARN: mod_auth_ldap: no AuthLDAPServer specified", NW_EL_WARNING);
             ldap_close($ld_cid);
             return false;
         }
     }
     $ld_dn = access_query("authldapbinddn", 0);
     $eu = explode("@", $user);
     $ld_dn = str_replace("%AUTH_USER%", $user, $ld_dn);
     $ld_dn = str_replace("%AUTH_USER_U%", $eu[0], $ld_dn);
     $ld_dn = str_replace("%AUTH_USER_D%", $eu[1], $ld_dn);
     if ($ld_bind = ldap_bind($ld_cid, $ld_dn, $pass)) {
         if ($ld_filter = access_query("authldapmatchfilter", 0)) {
             if ($ld_q = ldap_search($ld_cid, $ld_dn, $ld_filter)) {
                 if ($a = ldap_count_entries($ld_cid, $ld_q)) {
                     ldap_close($ld_cid);
                     return true;
                 } else {
                     ldap_close($ld_cid);
                     return false;
                 }
             } else {
                 ldap_close($ld_cid);
                 return false;
             }
         } else {
             ldap_close($ld_cid);
             return true;
         }
     } else {
         ldap_close($ld_cid);
         return false;
     }
 }
Example #29
0
 /**
  * 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);
 }
Example #30
0
 /**
  * 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);
         }
     }
 }