예제 #1
1
 protected function loadPage()
 {
     if (!ldap_control_paged_result($this->connection, $this->pageSize, true, $this->pageToken)) {
         throw new SearchException("Unable to set paged control pageSize: " . $this->pageSize);
     }
     $search = ldap_search($this->connection, $this->baseDn, $this->filter, is_array($this->attributes) ? $this->attributes : []);
     if (!$search) {
         // Something went wrong in search
         throw Connection::createLdapSearchException(ldap_errno($this->connection), $this->baseDn, $this->filter, $this->pageSize);
     }
     $this->entries = ldap_get_entries($this->connection, $search);
     $this->entriesPosition = 0;
     if (!$this->entries) {
         throw Connection::createLdapSearchException(ldap_errno($this->connection), $this->baseDn, $this->filter, $this->pageSize);
     }
     // check if on first page
     if (empty($this->pageToken)) {
         $this->currentPage = 0;
     } else {
         $this->currentPage++;
     }
     // Ok go to next page
     ldap_control_paged_result_response($this->connection, $search, $this->pageToken);
     if (empty($this->pageToken)) {
         $this->isLastPage = true;
     }
 }
예제 #2
0
 /**
  * Tries to connect to an LDAP server.
  *
  * If a connection is currently open, it is closed.
  *
  * All PHP errors triggered by ldap_* calls are wrapped in exceptions and thrown.
  *
  * @param string $serverHostName The hostname of the LDAP server.
  * @param int $port The server port to use.
  * @param int $timeout The timeout in seconds of the network connection.
  * @throws Exception If an error occurs during the `ldap_connect` call or if there is a connection
  *                   issue during the subsequent anonymous bind.
  */
 public function connect($serverHostName, $port = ServerInfo::DEFAULT_LDAP_PORT, $timeout = self::DEFAULT_TIMEOUT_SECS)
 {
     $this->closeIfCurrentlyOpen();
     Log::debug("Calling ldap_connect('%s', %s)", $serverHostName, $port);
     $this->connectionResource = ldap_connect($serverHostName, $port);
     ldap_set_option($this->connectionResource, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($this->connectionResource, LDAP_OPT_REFERRALS, 0);
     ldap_set_option($this->connectionResource, LDAP_OPT_NETWORK_TIMEOUT, $timeout);
     Log::debug("ldap_connect result is %s", $this->connectionResource);
     // ldap_connect will not always try to connect to the server, so execute a bind
     // to test the connection
     try {
         ldap_bind($this->connectionResource);
         Log::debug("anonymous ldap_bind call finished; connection ok");
     } catch (Exception $ex) {
         // if the error was due to a connection error, rethrow, otherwise ignore it
         $errno = ldap_errno($this->connectionResource);
         Log::debug("anonymous ldap_bind returned error '%s'", $errno);
         if (!in_array($errno, self::$initialBindErrorCodesToIgnore)) {
             throw $ex;
         }
     }
     if (!$this->isOpen()) {
         // sanity check
         throw new Exception("sanity check failed: ldap_connect did not return a connection resource!");
     }
 }
예제 #3
0
파일: Ldap.php 프로젝트: agentile/foresmo
 /**
  * 
  * Verifies a username handle and password.
  * 
  * @return mixed An array of verified user information, or boolean false
  * if verification failed.
  * 
  * 
  */
 protected function _processLogin()
 {
     // connect
     $conn = @ldap_connect($this->_config['uri']);
     // did the connection work?
     if (!$conn) {
         throw $this->_exception('ERR_CONNECTION_FAILED', $this->_config);
     }
     // upgrade to LDAP3 when possible
     @ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
     // filter the handle to prevent LDAP injection
     $regex = '/[^' . $this->_config['filter'] . ']/';
     $this->_handle = preg_replace($regex, '', $this->_handle);
     // bind to the server
     $rdn = sprintf($this->_config['format'], $this->_handle);
     $bind = @ldap_bind($conn, $rdn, $this->_passwd);
     // did the bind succeed?
     if ($bind) {
         ldap_close($conn);
         return array('handle' => $this->_handle);
     } else {
         $this->_err = @ldap_errno($conn) . " " . @ldap_error($conn);
         ldap_close($conn);
         return false;
     }
 }
예제 #4
0
 public function __construct($message, $ldapLink, $dn = null)
 {
     if ($ldapLink instanceof server) {
         $ldapLink = $ldapLink->getLink();
     }
     parent::__construct(sprintf('LDAP exception (%s): %s (%s)', $dn ? $dn : 'global', $message, @ldap_error($ldapLink), @ldap_errno($ldapLink)));
 }
예제 #5
0
파일: etape_ldap4.php 프로젝트: nursit/SPIP
function install_etape_ldap4_dist()
{
    $adresse_ldap = _request('adresse_ldap');
    $login_ldap = _request('login_ldap');
    $pass_ldap = _request('pass_ldap');
    $port_ldap = _request('port_ldap');
    $base_ldap = _request('base_ldap');
    $base_ldap_text = _request('base_ldap_text');
    if (!$base_ldap) {
        $base_ldap = $base_ldap_text;
    }
    echo install_debut_html();
    $ldap_link = ldap_connect($adresse_ldap, $port_ldap);
    @ldap_bind($ldap_link, $login_ldap, $pass_ldap);
    // Essayer de verifier le chemin fourni
    $r = @ldap_compare($ldap_link, $base_ldap, "objectClass", "");
    $fail = ldap_errno($ldap_link) == 32;
    if ($fail) {
        echo info_etape(_T('info_chemin_acces_annuaire')), info_progression_etape(3, 'etape_ldap', 'install/', true), "<div class='error'><p><b>" . _T('avis_operation_echec') . "</b></p><p>" . _T('avis_chemin_invalide_1'), " (<tt>" . htmlspecialchars($base_ldap) . "</tt>) " . _T('avis_chemin_invalide_2') . "</p></div>";
    } else {
        info_etape(_T('info_reglage_ldap'));
        echo info_progression_etape(4, 'etape_ldap', 'install/');
        $statuts = liste_statuts_ldap();
        $statut_ldap = defined('_INSTALL_STATUT_LDAP') ? _INSTALL_STATUT_LDAP : $GLOBALS['liste_des_statuts']['info_redacteurs'];
        $res = install_propager(array('adresse_ldap', 'port_ldap', 'login_ldap', 'pass_ldap', 'protocole_ldap', 'tls_ldap')) . "<input type='hidden' name='etape' value='ldap5' />" . "<input type='hidden' name='base_ldap' value='" . htmlentities($base_ldap) . "' />" . fieldset(_T('info_statut_utilisateurs_1'), array('statut_ldap' => array('label' => _T('info_statut_utilisateurs_2') . '<br />', 'valeur' => $statut_ldap, 'alternatives' => $statuts))) . install_ldap_correspondances() . bouton_suivant();
        echo generer_form_ecrire('install', $res);
    }
    echo install_fin_html();
}
예제 #6
0
 /**
  * @return string[]
  * @throws ValueRetrievalFailureException
  */
 public function parse()
 {
     if (!ldap_parse_reference($this->link, $this->reference, $referrals)) {
         throw new ValueRetrievalFailureException(ldap_error($this->link), ldap_errno($this->link));
     }
     return $referrals;
 }
예제 #7
0
파일: LdapResult.php 프로젝트: gossi/ldap
 /**
  * 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);
 }
예제 #8
0
 function __construct($arg, $code = 0)
 {
     if (is_resource($arg)) {
         $errno = ldap_errno($arg);
         $msg = ldap_err2str($errno);
     } else {
         $errno = $code;
         $msg = $arg;
     }
     error_log("LDAP Error {$errno}: {$msg}");
     parent::__construct($msg, $errno);
 }
예제 #9
0
 public function __construct($message, $ldap = NULL)
 {
     if (is_resource($ldap)) {
         $error = ldap_error($ldap);
         if ($error) {
             parent::__construct($message . '. ' . $error, ldap_errno($ldap));
         } else {
             parent::__construct($message);
         }
     } else {
         parent::__construct($message);
     }
 }
예제 #10
0
파일: Ldap.php 프로젝트: kalkin/solarphp
 /**
  * 
  * Fetch roles for a user.
  * 
  * @param string $handle Username to get roles for.
  * 
  * @return array An array of roles discovered in LDAP.
  * 
  */
 public function fetch($handle)
 {
     // connect
     $conn = @ldap_connect($this->_config['url']);
     // did the connection work?
     if (!$conn) {
         throw $this->_exception('ERR_CONNECTION_FAILED', array('url' => $this->_config['url']));
     }
     // upgrade to LDAP3 when possible
     @ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
     // bind to the server
     if ($this->_config['binddn']) {
         // authenticated bind
         $bind = @ldap_bind($conn, $this->_config['binddn'], $this->_config['bindpw']);
     } else {
         // anonumous bind
         $bind = @ldap_bind($conn);
     }
     // did we bind to the server?
     if (!$bind) {
         // not using $this->_exception() because we need fine control
         // over the error text
         throw Solar::exception(get_class($this), @ldap_errno($conn), @ldap_error($conn), array($this->_config));
     }
     // search for the groups
     $filter = sprintf($this->_config['filter'], $handle);
     $attrib = (array) $this->_config['attrib'];
     $result = ldap_search($conn, $this->_config['basedn'], $filter, $attrib);
     // get the first entry from the search result and free the result.
     $entry = ldap_first_entry($conn, $result);
     ldap_free_result($result);
     // now get the data from the entry and close the connection.
     $data = ldap_get_attributes($conn, $entry);
     ldap_close($conn);
     // go through the attribute data and add to the list. only
     // retain numeric keys; the ldap entry will have some
     // associative keys that are metadata and not useful to us here.
     $list = array();
     foreach ($attrib as $attr) {
         if (isset($data[$attr]) && is_array($data[$attr])) {
             foreach ($data[$attr] as $key => $val) {
                 if (is_int($key)) {
                     $list[] = $val;
                 }
             }
         }
     }
     // done!
     return $list;
 }
예제 #11
0
 public function getfromDn($dn, $noassoc = false)
 {
     $dn = $this->adescape($dn);
     $filter = "(&(objectCategory=group)(distinguishedname={$dn}))";
     $result = ldap_search($this->con, $this->dn, $filter, $this->attributes);
     if (ldap_errno($this->con)) {
         throw new searchException('Unable to conduct search: ' . ldap_error($this->con));
     }
     if (ldap_count_entries($this->con, $result) == 0) {
         $result = ldap_search($this->con2, $this->dn2, $filter, $this->attributes);
     }
     if (ldap_errno($this->con2)) {
         throw new searchException('Unable to conduct search: ' . ldap_error($this->con2));
     }
     return $this->parseResult($result, $noassoc);
 }
예제 #12
0
 /**
  *
  * @throws BadSearchFilterException
  * @throws NoSuchObjectException
  * @throws InvalidCredentialException
  * @throws AlreadyExistsException
  * @throws LdapException
  */
 public static function throwException(Connection $conn)
 {
     $error = ldap_error($conn->getResource());
     $code = ldap_errno($conn->getResource());
     switch ($code) {
         case -7:
             throw new BadSearchFilterException($error, $code);
         case 32:
             throw new NoSuchObjectException($error, $code);
         case 49:
             throw new InvalidCredentialException($error, $code);
         case 68:
             throw new AlreadyExistsException($error, $code);
     }
     throw new LdapException($error, $code);
 }
예제 #13
0
 /**
  * Connects to an LDAP server specified by $uri, with admin $user and $password.
  *
  * Returns a resource which can be used in LDAP functions like add, delete, search.
  *
  * @param string $uri Uri for LDAP, such as 'ldap://example.com'
  * @param string $format Format for an entry, like 'cn=%s,dc=example,dc=com'. %s is a literal placeholder for username
  * @param string $user Admin username
  * @param string $password Password for admin
  * @return resource
  */
 public static function connect($uri, $format, $user, $password)
 {
     if (!extension_loaded('ldap')) {
         die('LDAP extension is not loaded.');
     }
     $connection = ldap_connect($uri);
     if (!$connection) {
         throw new Exception("Could not connect to host '{$uri}'");
     }
     ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
     @ldap_bind($connection, sprintf($format, $user), $password);
     $err = ldap_errno($connection);
     switch ($err) {
         case 0x51:
             // LDAP_SERVER_DOWN
         // LDAP_SERVER_DOWN
         case 0x52:
             // LDAP_LOCAL_ERROR
         // LDAP_LOCAL_ERROR
         case 0x53:
             // LDAP_ENCODING_ERROR
         // LDAP_ENCODING_ERROR
         case 0x54:
             // LDAP_DECODING_ERROR
         // LDAP_DECODING_ERROR
         case 0x55:
             // LDAP_TIMEOUT
         // LDAP_TIMEOUT
         case 0x56:
             // LDAP_AUTH_UNKNOWN
         // LDAP_AUTH_UNKNOWN
         case 0x57:
             // LDAP_FILTER_ERROR
         // LDAP_FILTER_ERROR
         case 0x58:
             // LDAP_USER_CANCELLED
         // LDAP_USER_CANCELLED
         case 0x59:
             // LDAP_PARAM_ERROR
         // LDAP_PARAM_ERROR
         case 0x5a:
             // LDAP_NO_MEMORY
             throw new Exception("Could not connect to host '{$uri}'. (0x" . dechex($err) . ")");
             break;
     }
     return $connection;
 }
예제 #14
0
 function init()
 {
     try {
         write_log('identiteam', 'Initialising');
         # Load default config, and merge with users' settings
         $this->load_config('config-default.inc.php');
         $this->load_config('config.inc.php');
         $this->app = rcmail::get_instance();
         $this->config = $this->app->config->get('identiteam');
         # Load LDAP & mail config at once
         $this->ldap = $this->config['ldap'];
         $this->mail = $this->config['mail'];
         $this->server = $this->ldap['server'];
         $this->referr = $this->ldap['referrals'];
         $this->b_user = $this->ldap['bind_user'];
         $this->b_pass = $this->ldap['bind_pass'];
         $this->filter = $this->ldap['filter'];
         $this->domain = $this->ldap['domain'];
         # Get these fields
         $this->fields = explode(',', $this->ldap['fields']);
         array_push($this->fields, $this->ldap['extraEmailField']);
         $this->conn = ldap_connect($this->server);
         if (is_resource($this->conn)) {
             ldap_set_option($this->conn, LDAP_OPT_PROTOCOL_VERSION, 3);
             ldap_set_option($this->conn, LDAP_OPT_REFERRALS, $this->referr);
             $bound = ldap_bind($this->conn, $this->b_user, $this->b_pass);
             if ($bound) {
                 // Create signature
                 $this->add_hook('user2email', array($this, 'user2email'));
                 $this->initialised = true;
             } else {
                 $log = sprintf("Bind to server '%s' failed. Con: (%s), Error: (%s)", $this->server, $this->conn, ldap_errno($this->conn));
                 write_log('identiteam', $log);
             }
         } else {
             $log = sprintf("Connection to the server failed: (Error=%s)", ldap_errno($this->conn));
             write_log('identiteam', $log);
         }
     } catch (Exception $exc) {
         write_log('identiteam', 'Fail to initialise: ' . $exc->getMessage());
     }
     if ($this->initialised) {
         write_log('identiteam', 'Initialised');
     }
 }
 public function authenticate($ps_username, $ps_password = '', $pa_options = null)
 {
     $vo_bind = $this->bindToDirectory($ps_username, $ps_password);
     if (!$vo_bind) {
         if (ldap_get_option($this->getLinkIdentifier(), 0x32, $extended_error)) {
             $vs_bind_rdn = $this->getProcessedConfigValue("ldap_bind_rdn_format", $ps_username, "", "");
             caLogEvent("ERR", "LDAP ERROR (" . ldap_errno($this->getLinkIdentifier()) . ") {$extended_error} [{$vs_bind_rdn}]", "OpenLDAP::Authenticate");
         }
         return false;
     }
     // check group membership
     if (!$this->hasRequiredGroupMembership($ps_username)) {
         return false;
     }
     // user role and group membership syncing with directory
     $this->syncWithDirectory($ps_username);
     return true;
 }
예제 #16
0
 protected function retrieveResponse()
 {
     $response = $this->initResponse();
     $response->setCode($this->errorNo);
     $response->setResponseError($this->errorMsg);
     if (!$this->filter) {
         return $response;
     }
     $ds = $this->connectToServer();
     if (!$ds) {
         $response->setResponseError("Could not connect to LDAP server");
         return $response;
     }
     if ($this->adminDN) {
         if (!ldap_bind($ds, $this->adminDN, $this->adminPassword)) {
             Kurogo::log(LOG_WARNING, "Error binding to LDAP Server {$this->host} for {$this->adminDN}: " . ldap_error($ds), 'data');
             $response->setResponseError("Could not connect to LDAP server");
             return $response;
         }
     }
     // suppress warnings on non-dev servers
     // about searches that go over the result limit
     if (!$this->debugMode) {
         $error_reporting = ini_get('error_reporting');
         error_reporting($error_reporting & ~E_WARNING);
     }
     if ($this->filter instanceof LDAPFilter) {
         $result = @ldap_search($ds, $this->searchBase, strval($this->filter), $this->getAttributes(), 0, 0, $this->searchTimelimit);
     } else {
         $result = @ldap_read($ds, $this->filter, "(objectclass=*)", $this->getAttributes(), 0, 0, $this->readTimelimit);
     }
     $error_code = ldap_errno($ds);
     $response->setResponse($result);
     $response->setCode($error_code);
     $response->setContext('ldap', $ds);
     if ($error_code) {
         $response->setResponseError($this->generateErrorMessage($error_code));
     }
     if (!$this->debugMode) {
         error_reporting($error_reporting);
     }
     return $response;
 }
예제 #17
0
파일: Ads.php 프로젝트: nao-pon/impresscms
 /**
  *  Authenticate  user again LDAP directory (Bind)
  *  2 options :
  * 		Authenticate directly with uname in the DN
  * 		Authenticate with manager, search the dn
  *
  * @param string $uname Username
  * @param string $pwd Password
  *
  * @return bool
  */
 public function authenticate($uname, $pwd = null)
 {
     $authenticated = false;
     if (!extension_loaded('ldap')) {
         $this->setErrors(0, _AUTH_LDAP_EXTENSION_NOT_LOAD);
         return $authenticated;
     }
     $this->_ds = ldap_connect($this->ldap_server, $this->ldap_port);
     if ($this->_ds) {
         ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, $this->ldap_version);
         ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, 0);
         if ($this->ldap_use_TLS) {
             // We use TLS secure connection
             if (!ldap_start_tls($this->_ds)) {
                 $this->setErrors(0, _AUTH_LDAP_START_TLS_FAILED);
             }
         }
         // If the uid is not in the DN we proceed to a search
         // The uid is not always in the dn
         $userUPN = $this->getUPN($uname);
         if (!$userUPN) {
             return false;
         }
         // We bind as user to test the credentials
         $authenticated = ldap_bind($this->_ds, $userUPN, $this->cp1252_to_utf8(stripslashes($pwd)));
         if ($authenticated) {
             // We load the User database
             $dn = $this->getUserDN($uname);
             if ($dn) {
                 return $this->loadicms_member_user_Object($dn, $uname, $pwd);
             } else {
                 return false;
             }
         } else {
             $this->setErrors(ldap_errno($this->_ds), ldap_err2str(ldap_errno($this->_ds)) . '(' . $userUPN . ')');
         }
     } else {
         $this->setErrors(0, _AUTH_LDAP_SERVER_NOT_FOUND);
     }
     @ldap_close($this->_ds);
     return $authenticated;
 }
 function authenticate($params)
 {
     assert('isset($params["user"]) && isset($params["password"])');
     $con = false;
     if (($domain = getConfiguration('auth.ldap.domain')) !== false) {
         $port = (int) getConfiguration('auth.ldap.port', self::LDAP_DEFAULT_PORT);
         $con = ldap_connect($domain, $port);
     }
     if ($con === false) {
         throw new Exception(__METHOD__ . ": Failed to connect to {$domain} in port {$port}");
     }
     $authUser = $user = $this->ldap_escape($params['user']);
     $pass = $this->ldap_escape($params['password']);
     $ldapDomainName = getConfiguration('auth.ldap.domain.name');
     if ($ldapDomainName) {
         $authUser = $ldapDomainName . '\\' . $authUser;
     }
     debug(__METHOD__ . ": Trying to authenticate {$authUser} against {$domain}");
     if (ldap_bind($con, $authUser, $pass)) {
         // We're assuming that the email used is as the user name
         $email = $email = Utils::buildEmail($user);
         // Close the connection - we don't need it any more
         ldap_unbind($con);
         // Fetch contact
         $contact = DatabaseHelper::getInstance()->getContactByEmail($email);
         if ($contact !== false) {
             return array('Id' => $contact['Id'], 'Role' => $contact['Role']);
         } else {
             // Contact is not in the database - we better create it
             // TODO: Put the option to read data
             return array('Id' => DatabaseHelper::getInstance()->addContact('', '', $email, ROLE_IDENTIFIED), 'Role' => ROLE_IDENTIFIED);
         }
     } else {
         $errCode = ldap_errno($con);
         if ($errCode == self::LDAP_INAPPROPRIATE_AUTH || $errCode == self::LDAP_INVALID_CREDENTIALS) {
             // Invalid credentials - simply fail
             return false;
         }
         // Internal error
         throw new Exception(__METHOD__ . " : LDAP error: " . ldap_err2str($errCode));
     }
 }
function moveuser()
{
    $u = new user($_POST["userid"]);
    $dn = $u->dn;
    $gplist = $u->Groups_list();
    if (preg_match("#^(.+?),#", $dn, $re)) {
        $newRdn = $re[1];
    } else {
        $newRdn = "cn={$_POST["userid"]}";
    }
    $ldap = new clladp();
    $newParent = "ou=users,ou={$_POST["nextou"]},dc=organizations,{$ldap->suffix}";
    if (!ldap_rename($ldap->ldap_connection, $dn, $newRdn, $newParent, true)) {
        echo 'Error number ' . ldap_errno($ldap->ldap_connection) . "\nAction:LDAP Ldap_rename\ndn:{$dn} -> {$newRdn},{$newParent}\n" . ldap_err2str(ldap_errno($ldap->ldap_connection));
        return;
    }
    while (list($gid, $name) = each($gplist)) {
        $gp = new groups($gid);
        $gp->DeleteUserFromThisGroup($_POST["userid"]);
    }
}
예제 #20
0
function delete_ldap($dn, $connect, $recursive = false)
{
    if ($recursive == false) {
        if (!@ldap_delete($connect, $dn)) {
            echo "Deleting {$dn}...\n";
            echo "ERROR: ldap_delete \"{$dn}\"" . ldap_err2str(ldap_errno($connect)) . "\n";
            return false;
        }
    }
    $sr = @ldap_list($connect, $dn, "ObjectClass=*");
    if ($sr) {
        $info = @ldap_get_entries($connect, $sr);
        for ($i = 0; $i < $info['count']; $i++) {
            $result = delete_ldap($info[$i]['dn'], $connect, $recursive);
            if (!$result) {
                return $result;
            }
        }
        return delete_ldap($dn, $connect, false);
    }
}
예제 #21
0
function login($dn, $password)
{
    global $ldap_connection;
    global $ldap_error;
    $ldap_host = "ldap://192.168.30.190";
    $ldap_port = "389";
    $ldap_user = $dn;
    $ldap_pwd = $password;
    $ldap_connection = ldap_connect($ldap_host, $ldap_port) or die("Can't connect to LDAP server");
    @ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
    @ldap_bind($ldap_connection, $ldap_user, $ldap_pwd);
    if (ldap_errno($ldap_connection) != 0) {
        //echo "Can't log in! ".ldap_error($ldap_connection)."<br>";
        //$_SERVER['PHP_AUTH_USER']= "";
        //@ldap_unbind($ldap_conn);
        $ldap_error = ldap_error($ldap_connection);
        return 1;
    } else {
        return 0;
    }
}
예제 #22
0
파일: Response.php 프로젝트: alaneor/ldap
 public function __construct(Ldap $link, $result = null)
 {
     $this->result = $result;
     if (is_resource($result)) {
         // Get the status code, matched DN and referrals from the response
         ldap_parse_result($link->resource(), $result, $this->code, $this->matchedDN, $this->message, $this->referrals);
         // Get the string representation of the status code
         $this->message = ldap_err2str($this->code);
         // Extract the data from the resource
         $this->data = ldap_get_entries($link->resource(), $result);
         $this->data = $this->cleanup_result($this->data);
         // Remove the referrals array if there's nothing inside
         count($this->referrals) == 0 && ($this->referrals = null);
         // Try to extract pagination cookie and estimated number of objects to be returned
         // Since there's no way to tell if pagination has been enabled or not, I am suppressing php errors
         @ldap_control_paged_result_response($link->resource(), $result, $this->cookie, $this->estimated);
     } else {
         $this->code = ldap_errno($link->resource());
         $this->message = ldap_error($link->resource());
     }
     // Active Directory conceals some additional error codes in the ErrorMessage of the response
     // that we cannot get to with ldap_errno() in authentication failures - let's try to
     // extract them!
     if ($this->code == 49) {
         $message = null;
         ldap_get_option($link->resource(), Option::ErrorString, $message);
         if (stripos($message, 'AcceptSecurityContext') !== false) {
             $message = explode(', ', $message);
             end($message);
             $message = prev($message);
             $this->code = explode(' ', $message)[1];
             // For compatibility reasons with standard ldap, if the error code
             // is 52e let's replace it with 49 ( their meanings are equal, it's just
             // Microsoft doing it its own way again )
             if ($this->code == '52e') {
                 $this->code = ResponseCode::InvalidCredentials;
             }
         }
     }
 }
예제 #23
0
 /**
  * Runs a standard search on LDAP
  *
  * @param string $queryString
  * @param string $context
  * @return beautified LDAP result set
  * @throws Ncstate_Service_Exception on LDAP Error
  */
 public function search($queryString, $context, $returnFields, $sortKey = null, $sortOrder = null)
 {
     // Make sure there are some return fields set
     if (count($returnFields) == 0) {
         $returnFields = array('*', '+');
     }
     // Do the search
     $ldapResult = @ldap_search($this->getLink(), $context, $queryString, $returnFields, 0, $this->_maxResults);
     if (!$ldapResult) {
         throw new Ncstate_Service_Exception(ldap_error($this->_link), ldap_errno($this->_link));
     }
     // Return empty array if there are no etries
     if (@ldap_count_entries($this->getLink(), $ldapResult) == 0) {
         return array();
     }
     $result = @ldap_get_entries($this->getLink(), $ldapResult);
     unset($result["count"]);
     $ret = array();
     foreach ($result as $r) {
         $temp = array();
         $keys = array_keys($r);
         foreach ($keys as $k) {
             if (!is_int($k) && $k != "dn" && $k != "count") {
                 if (is_array($r[$k])) {
                     $temp[$k] = $r[$k][0];
                 } else {
                     $temp[$k] = $r[$k];
                 }
             }
         }
         $ret[] = $temp;
     }
     if (!is_null($sortKey)) {
         usort($ret, create_function('$a, $b', "return strnatcasecmp(\$a['{$sortKey}'], \$b['{$sortKey}']);"));
         if ($sortOrder == "desc") {
             $ret = array_reverse($ret);
         }
     }
     return $ret;
 }
예제 #24
0
 public static function authenticateLdapMember($strUsername, $strPassword)
 {
     $objLdapUser = LdapMemberModel::findLdapMember($strUsername);
     if ($objLdapUser) {
         if (!@ldap_bind(Ldap::getConnection(), $objLdapUser->dn, $strPassword)) {
             $errno = ldap_errno(Ldap::getConnection());
             switch ($errno) {
                 case static::LDAP_INVALID_CREDENTIALS:
                     return false;
             }
             return false;
         }
         // ldap account requires an valid email and uid
         if ($objLdapUser->uid['count'] == 0 || $objLdapUser->mail['count'] == 0) {
             \Message::addError($GLOBALS['TL_LANG']['MSC']['ldap']['emailUidMissing']);
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
예제 #25
0
 function bindCheck($username, $password)
 {
     if (!function_exists("ldap_connect")) {
         $this->errorString = "This PHP doesn't support LDAP, check the result of infophp() function.";
         return false;
     }
     $this->errorString = "";
     if (!$this->isActive) {
         $this->errorString = "LDAP Setting isn't supplied.";
         return false;
     }
     if (!$username || !$password) {
         $this->errorString = "Account Info isn't supplied.";
         return false;
     }
     $ds = ldap_connect($this->server, $this->port);
     if (!$ds) {
         $this->errorString = ldap_err2str(ldap_errno($ds));
         return false;
     }
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
     $rdn = "{$this->accountKey}={$username},{$this->container},{$this->base}";
     try {
         $currentErrorReporting = error_reporting();
         error_reporting(0);
         $r = ldap_bind($ds, $rdn, $password);
         error_reporting($currentErrorReporting);
     } catch (Exception $e) {
         $this->errorString = ldap_err2str(ldap_errno($ds)) . " by {$rdn}";
         $r = false;
     }
     ldap_close($ds);
     if (strlen($this->errorString)) {
         $this->logger->setErrorMessage($this->errorString);
     }
     return $r;
 }
예제 #26
0
파일: Driver.php 프로젝트: 81square/ldap
 /**
  * Connects to a Ldap directory without binding
  *
  * @param string  $hostname Hostname to connect to
  * @param int     $port     Port to connect to (Default: 389)
  * @param boolean $withSSL  Whether to connect with SSL support (Default: false)
  * @param boolean $withTLS  Whether to connect with TLS support (Default: false)
  *
  * @return ConnectionInterface connection instance
  *
  * @throws ConnectionException if connection fails
  */
 public function connect($hostname, $port = 389, $withSSL = false, $withTLS = false)
 {
     if ($withSSL && $withTLS) {
         throw new ConnectionException('Cannot support both TLS & SSL for a given Ldap Connection');
     }
     if (!extension_loaded('ldap') && !@dl('ldap.' . PHP_SHLIB_SUFFIX)) {
         throw new ConnectionException('You do not have the required ldap-extension installed');
     }
     if ($withSSL) {
         $hostname = 'ldaps://' . $hostname;
     }
     $connection = @ldap_connect($hostname, $port);
     if (false === $connection) {
         throw new ConnectionException('Could not successfully connect to the LDAP server');
     }
     if ($withTLS) {
         if (!@ldap_start_tls($connection)) {
             $code = @ldap_errno($connection);
             throw new ConnectionException(sprintf('Could not start TLS: Ldap Error Code=%s - %s', $code, ldap_err2str($code)));
         }
     }
     return new Connection($connection);
 }
예제 #27
0
 /**
  * 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));
 }
예제 #28
0
파일: Ldap.php 프로젝트: jubinpatel/horde
 /**
  * Sets a script running on the backend.
  *
  * @param array $script  The filter script information. Passed elements:
  *                       - 'name': (string) the script name.
  *                       - 'recipes': (array) the filter recipe objects.
  *                       - 'script': (string) the filter script.
  *
  * @throws Ingo_Exception
  */
 public function setScriptActive($script)
 {
     $ldapcn = $this->_connect();
     $values = $this->_getScripts($ldapcn, $userDN);
     $found = false;
     foreach ($values as $i => $value) {
         if (strpos($value, "# Sieve Filter\n") !== false) {
             if (empty($script['script'])) {
                 unset($values[$i]);
             } else {
                 $values[$i] = $script['script'];
             }
             $found = true;
             break;
         }
     }
     if (!$found && !empty($script['script'])) {
         $values[] = $script['script'];
     }
     $replace = array(Horde_String::lower($this->_params['script_attribute']) => $values);
     $r = empty($values) ? @ldap_mod_del($ldapcn, $userDN, $replace) : @ldap_mod_replace($ldapcn, $userDN, $replace);
     if (!$r) {
         throw new Ingo_Exception(sprintf(_("Activating the script for \"%s\" failed: (%d) %s"), $userDN, ldap_errno($ldapcn), ldap_error($ldapcn)));
     }
     @ldap_close($ldapcn);
 }
예제 #29
0
 /**
  * @param mixed $mReturn
  * @return mixed
  */
 private function validateLdapErrorOnFalse($mReturn)
 {
     if (false === $mReturn) {
         if ($this->rLink) {
             CApi::Log('LDAP: error #' . @ldap_errno($this->rLink) . ': ' . @ldap_error($this->rLink), ELogLevel::Error);
         } else {
             CApi::Log('LDAP: unknown ldap error', ELogLevel::Error);
         }
     }
     return $mReturn;
 }
예제 #30
0
 /**
  * Bind to LDAP with a specific DN and password. Simple wrapper around
  * ldap_bind() with some additional logging.
  *
  * @param string $dn
  * The DN used.
  * @param string $password
  * The password used.
  * @param array $sasl_args
  * Array of SASL options for SASL bind
  * @return bool
  * Returns TRUE if successful, FALSE if
  * LDAP_INVALID_CREDENTIALS, LDAP_X_PROXY_AUTHZ_FAILURE,
  * LDAP_INAPPROPRIATE_AUTH, LDAP_INSUFFICIENT_ACCESS
  * @throws SimpleSAML_Error_Exception on other errors
  */
 public function bind($dn, $password, array $sasl_args = NULL)
 {
     $authz_id = null;
     if ($sasl_args != NULL) {
         if (!function_exists('ldap_sasl_bind')) {
             $ex_msg = 'Library - missing SASL support';
             throw $this->makeException($ex_msg);
         }
         // SASL Bind, with error handling.
         $authz_id = $sasl_args['authz_id'];
         $error = @ldap_sasl_bind($this->ldap, $dn, $password, $sasl_args['mech'], $sasl_args['realm'], $sasl_args['authc_id'], $sasl_args['authz_id'], $sasl_args['props']);
     } else {
         // Simple Bind, with error handling.
         $authz_id = $dn;
         $error = @ldap_bind($this->ldap, $dn, $password);
     }
     if ($error === TRUE) {
         // Good.
         $this->authz_id = $authz_id;
         SimpleSAML_Logger::debug('Library - LDAP bind(): Bind successful with DN \'' . $dn . '\'');
         return TRUE;
     }
     /* Handle errors
      * LDAP_INVALID_CREDENTIALS
      * LDAP_INSUFFICIENT_ACCESS */
     switch (ldap_errno($this->ldap)) {
         case 32:
             /* LDAP_NO_SUCH_OBJECT */
         /* LDAP_NO_SUCH_OBJECT */
         case 47:
             /* LDAP_X_PROXY_AUTHZ_FAILURE */
         /* LDAP_X_PROXY_AUTHZ_FAILURE */
         case 48:
             /* LDAP_INAPPROPRIATE_AUTH */
         /* LDAP_INAPPROPRIATE_AUTH */
         case 49:
             /* LDAP_INVALID_CREDENTIALS */
         /* LDAP_INVALID_CREDENTIALS */
         case 50:
             /* LDAP_INSUFFICIENT_ACCESS */
             return FALSE;
             break;
         default:
             break;
     }
     // Bad.
     throw $this->makeException('Library - LDAP bind(): Bind failed with DN \'' . $dn . '\'');
 }