Exemple #1
0
 /**
  * @brief reads a given attribute for an LDAP record identified by a DN
  * @param $dn the record in question
  * @param $attr the attribute that shall be retrieved
  * @returns the values in an array on success, false otherwise
  *
  * Reads an attribute from an LDAP entry
  */
 public function readAttribute($dn, $attr)
 {
     if (!$this->checkConnection()) {
         \OCP\Util::writeLog('user_ldap', 'No LDAP Connector assigned, access impossible for readAttribute.', \OCP\Util::WARN);
         return false;
     }
     $cr = $this->connection->getConnectionResource();
     if (!is_resource($cr)) {
         //LDAP not available
         \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
         return false;
     }
     $rr = @ldap_read($cr, $dn, 'objectClass=*', array($attr));
     if (!is_resource($rr)) {
         \OCP\Util::writeLog('user_ldap', 'readAttribute ' . $attr . ' failed for DN ' . $dn, \OCP\Util::DEBUG);
         //in case an error occurs , e.g. object does not exist
         return false;
     }
     $er = ldap_first_entry($cr, $rr);
     //LDAP attributes are not case sensitive
     $result = \OCP\Util::mb_array_change_key_case(ldap_get_attributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
     $attr = mb_strtolower($attr, 'UTF-8');
     if (isset($result[$attr]) && $result[$attr]['count'] > 0) {
         $values = array();
         for ($i = 0; $i < $result[$attr]['count']; $i++) {
             $values[] = $this->resemblesDN($attr) ? $this->sanitizeDN($result[$attr][$i]) : $result[$attr][$i];
         }
         return $values;
     }
     \OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, \OCP\Util::DEBUG);
     return false;
 }
Exemple #2
0
 /**
  * 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;
 }
 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)));
     }
 }
 /**
  * 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;
 }
Exemple #5
0
 /**
  * Binds/authenticates the user to LDAP, and returns their attributes.
  *
  * @author [A. Gianotto] [<*****@*****.**>]
  * @since [v3.0]
  * @param $username
  * @param $password
  * @param bool|false $user
  * @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 $user is true
  *
  */
 static function findAndBindUserLdap($username, $password)
 {
     $settings = Setting::getSettings();
     $connection = Ldap::connectToLdap();
     $ldap_username_field = $settings->ldap_username_field;
     $baseDn = $settings->ldap_basedn;
     if ($settings->is_ad == '1') {
         // In case they haven't added an AD domain
         if ($settings->ad_domain == '') {
             $userDn = $username . '@' . $settings->email_domain;
         } else {
             $userDn = $username . '@' . $settings->ad_domain;
         }
     } else {
         $userDn = $ldap_username_field . '=' . $username . ',' . $settings->ldap_basedn;
     }
     $filterQuery = $settings->ldap_auth_filter_query . $username;
     if (!($ldapbind = @ldap_bind($connection, $userDn, $password))) {
         return false;
     }
     if (!($results = ldap_search($connection, $baseDn, $filterQuery))) {
         throw new Exception('Could not search LDAP: ');
     }
     if (!($entry = ldap_first_entry($connection, $results))) {
         return false;
     }
     if (!($user = array_change_key_case(ldap_get_attributes($connection, $entry), CASE_LOWER))) {
         return false;
     }
     return $user;
 }
 public function __construct($user)
 {
     $this->_id = $user;
     /* Connect to the IU's ADS server */
     $ds = ldap_connect(LDAP_HOST, LDAP_PORT) or die("Could not connect to ads.iu.edu:636 server");
     ldap_bind($ds, LDAP_USER . "," . LDAP_BASEDN, LDAP_PWD) or die("LDAP bind to ADS failed.");
     /* Search for a particular user information (Only required info) */
     $reqatr = array("mail", "displayName", "givenName", "title");
     $result = ldap_search($ds, LDAP_BASEDN, "(sAMAccountName={$this->_id})", $reqatr) or die("Search: No ADS entry has been found for the current user.");
     /* Each node in a directory tree has an entry. */
     $entry = ldap_first_entry($ds, $result);
     while ($entry) {
         /* Each entry is a set of attribute value pairs */
         /* Extracting only required values              */
         /* Also assuming there is only single value     */
         $this->_email = ldap_get_values($ds, $entry, "mail");
         $this->_email = $this->_email[0];
         /* Php 5.3 */
         $this->_name = ldap_get_values($ds, $entry, "displayName");
         if (is_null($this->_name)) {
             $this->_name = ldap_get_values($ds, $entry, "givenName");
         }
         $this->_name = $this->_name[0];
         /* Php 5.3 */
         $this->_instructor = ldap_get_values($ds, $entry, "title");
         $this->_instructor = $this->_instructor[0];
         /* Not expecting multiple entries */
         /* $entry = ldap_next_entry($ds, $result); */
         $entry = null;
     }
 }
Exemple #7
0
 function verify($cert, $dn)
 {
     $conn = ldap_connect($this->LDAP_HOST);
     if (!$conn) {
         return false;
     }
     if (!ldap_bind($conn)) {
         return false;
     }
     $resultset = ldap_search($conn, "c=EE", "(serialNumber=38212200301)");
     if (!$resultset) {
         echo "No recs";
         return false;
     }
     $rec = ldap_first_entry($conn, $resultset);
     while ($rec !== false) {
         $values = ldap_get_values($conn, $rec, 'usercertificate;binary');
         $certificate = "-----BEGIN CERTIFICATE-----\n" . chunk_split(base64_encode($values[0]), 64, "\n") . "-----END CERTIFICATE-----\n";
         if (strcmp($cert, $certificate) == 0) {
             return "Found";
         }
         $rec = ldap_next_entry($conn, $rec);
     }
     // Not found a record with a matching certificate
     return false;
 }
Exemple #8
0
 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
 }
 function get_user_old_ldap($email)
 {
     $attributes = ["uid" => "uid", "mail" => "mail", "givenName" => "firstname", "sn" => "lastname", "displayName" => "nick", "gender" => "gender", "birthdate" => "dob", "o" => "organization", "c" => "country", "l" => "location"];
     $this->load_library("ldap_lib", "ldap");
     $ds = $this->ldap->get_link();
     $dn = "dc=felicity,dc=iiit,dc=ac,dc=in";
     $filter = '(&(mail=' . $email . '))';
     $sr = ldap_search($ds, $dn, $filter, array_keys($attributes));
     $entry = ldap_first_entry($ds, $sr);
     if (!$entry) {
         return false;
     }
     $entry_data = ldap_get_attributes($ds, $entry);
     $user_data = [];
     foreach ($attributes as $key => $value) {
         if (isset($entry_data[$key]) && isset($entry_data[$key][0])) {
             $user_data[$value] = $entry_data[$key][0];
         }
     }
     if (isset($user_data["dob"])) {
         $date = date_create_from_format('d/m/Y', $user_data["dob"]);
         if ($date) {
             $user_data["dob"] = date_format($date, "Y-m-d");
         }
     }
     if (isset($user_data["firstname"]) && isset($user_data["lastname"])) {
         $user_data["name"] = implode(" ", [$user_data["firstname"], $user_data["lastname"]]);
         unset($user_data["firstname"]);
         unset($user_data["lastname"]);
     }
     if (isset($user_data["gender"])) {
         $user_data["gender"] = strtolower($user_data["gender"]);
     }
     return $user_data;
 }
 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;
 }
 /**
  * @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;
 }
Exemple #12
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;
}
Exemple #13
0
 /**
  * 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);
 }
Exemple #14
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);
     }
 }
Exemple #15
0
 public function fetch_row()
 {
     if ($this->get_opt('fetch_pos')) {
         return ldap_next_entry($this->handle, $this->resource);
     } else {
         return ldap_first_entry($this->handle, $this->resource);
     }
 }
 function login($user, $pass, $host, $port, &$err)
 {
     if ($this->ldapConn) {
         $err = "You are already logged in.  Please logout first.";
         return false;
     } else {
         if (!$host || !$user || !$pass) {
             $err = "Must specify a host, user, and pass.";
             return false;
         } else {
             if (!$port) {
                 $port = self::DEFAULT_LDAP_PORT;
             }
         }
     }
     $conn = ldap_connect($host, $port);
     if (!$conn) {
         $err = "Unable to connect to LDAP host [{$host}] on port [{$port}].";
         return false;
     }
     $ldapBind = ldap_bind($conn, $user, $pass);
     if (!$ldapBind) {
         $err = "Wrong Username and/or Password.";
         ldap_unbind($conn);
         return false;
     }
     // Confirm that the provided username is truly a username.
     $attrs = array('uid', 'gidnumber');
     // BASE_DN must be empty, because o=senate will miss those persons
     // who have the OU attribute in their DN.
     $sr = ldap_list($conn, self::DEFAULT_BASE_DN, "uid={$user}", $attrs);
     if (!$sr) {
         $err = "Unable to validate username.";
         ldap_unbind($conn);
         return false;
     }
     $ent_count = ldap_count_entries($conn, $sr);
     if ($ent_count !== 1) {
         $err = "Login [{$user}] is not a valid username.";
         ldap_unbind($conn);
         return false;
     }
     $ent = ldap_first_entry($conn, $sr);
     $uids = ldap_get_values($conn, $ent, "uid");
     if ($uids['count'] > 1 || $uids[0] != $user) {
         $err = "Provided username does not match looked-up username.";
         ldap_unbind($conn);
         return false;
     }
     $gids = ldap_get_values($conn, $ent, "gidnumber");
     unset($gids['count']);
     $groupNames = $this->convertGroupIdsToNames($conn, $gids);
     $this->ldapConn = $conn;
     $this->ldapUser = $user;
     $this->groupNames = $groupNames;
     $err = null;
     return true;
 }
 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;
 }
Exemple #18
0
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;
}
Exemple #19
0
 /**
  * @return Entry|null
  * @throws EntryRetrievalFailureException
  */
 public function firstEntry()
 {
     if (!($entry = ldap_first_entry($this->link, $this->result))) {
         if (0 !== ($errNo = ldap_errno($this->link))) {
             throw new EntryRetrievalFailureException(ldap_error($this->link), $errNo);
         }
         return null;
     }
     return new Entry($this->link, $entry);
 }
Exemple #20
0
 public function fetch($entryResource = NULL)
 {
     if (!$this->resource) {
         return FALSE;
     }
     if ($entryResource === NULL) {
         $entryResource = ldap_first_entry($this->connection->resource, $this->resource);
     }
     return new LdapRecord($this, $entryResource);
 }
 /**
  * Gets first entry
  *
  * @return  peer.ldap.LDAPEntry or FALSE if none exists by this offset
  * @throws  peer.ldap.LDAPException in case of a read error
  */
 public function getFirstEntry()
 {
     $this->entry = array(ldap_first_entry($this->_hdl, $this->_res));
     if (FALSE === $this->entry[0]) {
         if (!($e = ldap_errno($this->_hdl))) {
             return FALSE;
         }
         throw new LDAPException('Could not fetch first result entry.', $e);
     }
     $this->entry[1] = 1;
     return LDAPEntry::fromResource($this->_hdl, $this->entry[0]);
 }
 function getObjectSid($adConn, $dn, $distname)
 {
     //Select which attributes wa want
     $attrs = array("objectsid");
     //Filter creation
     $filter = "distinguishedname=" . addslashes($distname);
     //Do the seacrh!
     $search = ldap_search($adConn, $dn, $filter, $attrs) or die("**** happens, no connection!");
     $entry = ldap_first_entry($adConn, $search);
     $vals = ldap_get_values_len($adConn, $entry, "objectsid");
     return bin2hex($vals[0]);
 }
Exemple #23
0
 public function studentid2uid($pStudentId)
 {
     if (empty($pStudentId)) {
         throw new Exception("No parameter given", E_PARAM);
     }
     $dn = LDAP_OU . ", " . LDAP_O . ", " . LDAP_C;
     $filter = "(&(objectclass=" . LDAP_OBJECTCLASS_STUDENT . ")(" . LDAP_ATTRIBUTE_STUDID . "=" . $pStudentId . "))";
     $search = ldap_search($this->ldap_conn, $dn, $filter, array("uid"));
     $entry = ldap_first_entry($this->ldap_conn, $search);
     $result = @ldap_get_values($this->ldap_conn, $entry, "uid");
     ldap_free_result($search);
     return $result[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;
 }
Exemple #25
0
 /**
  * Auxiliar directo de busqueda. Dado un ldap result, itera por el para conseguir sus datos
  * 
  * @param ldap result $busquedaLdap
  * @param array $atributos
  * @return boolean
  */
 private function iterarEntradas($busquedaLdap, array $atributos)
 {
     $datos = array();
     if ($entrada = ldap_first_entry($this->conexionLdap, $busquedaLdap)) {
         do {
             // Ejecutamos al menos una vez el mapeo de entradas con sus atributos, a menos
             // que no haya nada
             $datos[] = $this->mapa($atributos, $entrada);
         } while ($entrada = ldap_next_entry($this->conexionLdap, $entrada));
         return $datos;
     } else {
         return FALSE;
     }
 }
Exemple #26
0
 /**
  * @brief reads a given attribute for an LDAP record identified by a DN
  * @param $dn the record in question
  * @param $attr the attribute that shall be retrieved
  *        if empty, just check the record's existence
  * @returns an array of values on success or an empty
  *          array if $attr is empty, false otherwise
  *
  * Reads an attribute from an LDAP entry or check if entry exists
  */
 public function readAttribute($dn, $attr, $filter = 'objectClass=*')
 {
     if (!$this->checkConnection()) {
         \OCP\Util::writeLog('user_ldap', 'No LDAP Connector assigned, access impossible for readAttribute.', \OCP\Util::WARN);
         return false;
     }
     $cr = $this->connection->getConnectionResource();
     if (!is_resource($cr)) {
         //LDAP not available
         \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
         return false;
     }
     $dn = $this->DNasBaseParameter($dn);
     $rr = @ldap_read($cr, $dn, $filter, array($attr));
     if (!is_resource($rr)) {
         if (!empty($attr)) {
             //do not throw this message on userExists check, irritates
             \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
         }
         //in case an error occurs , e.g. object does not exist
         return false;
     }
     if (empty($attr)) {
         \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
         return array();
     }
     $er = ldap_first_entry($cr, $rr);
     if (!is_resource($er)) {
         //did not match the filter, return false
         return false;
     }
     //LDAP attributes are not case sensitive
     $result = \OCP\Util::mb_array_change_key_case(ldap_get_attributes($cr, $er), MB_CASE_LOWER, 'UTF-8');
     $attr = mb_strtolower($attr, 'UTF-8');
     if (isset($result[$attr]) && $result[$attr]['count'] > 0) {
         $values = array();
         for ($i = 0; $i < $result[$attr]['count']; $i++) {
             if ($this->resemblesDN($attr)) {
                 $values[] = $this->sanitizeDN($result[$attr][$i]);
             } elseif (strtolower($attr) == 'objectguid' || strtolower($attr) == 'guid') {
                 $values[] = $this->convertObjectGUID2Str($result[$attr][$i]);
             } else {
                 $values[] = $result[$attr][$i];
             }
         }
         return $values;
     }
     \OCP\Util::writeLog('user_ldap', 'Requested attribute ' . $attr . ' not found for ' . $dn, \OCP\Util::DEBUG);
     return false;
 }
 /**
  * Gets first entry
  *
  * @return  peer.ldap.LDAPEntry or NULL if nothing was found
  * @throws  peer.ldap.LDAPException in case of a read error
  */
 public function first()
 {
     $entry = ldap_first_entry($this->conn, $this->result);
     if (!$entry) {
         if ($e = ldap_errno($this->conn)) {
             throw new LDAPException('Could not fetch first result entry.', $e);
         }
         return null;
         // Nothing found
     } else {
         $this->iteration = [$entry, 1];
         return LDAPEntry::create(ldap_get_dn($this->conn, $entry), ldap_get_attributes($this->conn, $entry));
     }
 }
Exemple #28
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);
 }
Exemple #29
0
 protected function search($ldap, $user)
 {
     $srch = ldap_search($ldap, 'DC=' . implode(',DC=', explode('.', $this->domain)), '(&(objectclass=person)(|(userprincipalname=' . $user . ')(distinguishedname=' . $user . '))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))');
     $data = ldap_first_entry($ldap, $srch);
     if (!$data) {
         return null;
     }
     $temp = [];
     foreach (ldap_get_attributes($ldap, $data) as $k => $v) {
         if ($v && isset($v['count']) && $v['count'] === 1) {
             $temp[$k] = $v[0];
         }
     }
     return $temp;
 }
Exemple #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);
         }
     }
 }