Exemplo n.º 1
0
 public function __construct($message, $handler, $extra_error = null)
 {
     $this->handler = $handler;
     $err_no = ldap_errno($handler);
     $message = sprintf("ERROR %s. LDAP ERROR (%s) -- %s --. %s", $message, $err_no, ldap_err2str($err_no), ldap_error($handler), is_null($extra_error) ? '' : $extra_error);
     parent::__construct($message, $err_no);
 }
Exemplo n.º 2
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);
 }
 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));
     }
 }
Exemplo n.º 4
0
 /**
  *  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 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"]);
    }
}
Exemplo n.º 6
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);
    }
}
Exemplo n.º 7
0
 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;
             }
         }
     }
 }
Exemplo n.º 8
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;
 }
Exemplo n.º 9
0
 /**
  * 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);
 }
Exemplo n.º 10
0
function ldapLoginBindFailure($ldapc)
{
    global $Conf, $email_class, $password_class;
    // connection failed, report error
    $lerrno = ldap_errno($ldapc);
    $suffix = "";
    if ($lerrno != 49) {
        $suffix = "<br /><span class='hint'>(LDAP error {$lerrno}: " . htmlspecialchars(ldap_err2str($lerrno)) . ")</span>";
    }
    if ($lerrno < 5) {
        return Conf::msg_error("LDAP protocol error.  Logins will fail until this error is fixed.{$suffix}");
    } else {
        if (req_s("password") == "") {
            $password_class = " error";
            if ($lerrno == 53) {
                $suffix = "";
            }
            return Conf::msg_error("Enter your LDAP password.{$suffix}");
        } else {
            $email_class = $password_class = " error";
            return Conf::msg_error("Those credentials are invalid.  Please use your LDAP username and password.{$suffix}");
        }
    }
}
Exemplo n.º 11
0
 function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE)
 {
     $userdn = $userdn != NULL ? $userdn : $this->binddn;
     $pass = $pass != NULL ? $pass : $this->bindpw;
     if (!isset($this->testUsers[$userdn])) {
         $ldap_errno = LDAP_NO_SUCH_OBJECT;
         if (function_exists('ldap_err2str')) {
             $ldap_error = ldap_err2str($ldap_errno);
         } else {
             $ldap_error = "Failed to find {$userdn} in LdapServerTest.class.php";
         }
     } elseif (isset($this->testUsers[$userdn]['attr']['password'][0]) && $this->testUsers[$userdn]['attr']['password'][0] != $pass) {
         $ldap_errno = LDAP_INVALID_CREDENTIALS;
         if (function_exists('ldap_err2str')) {
             $ldap_error = ldap_err2str($ldap_errno);
         } else {
             $ldap_error = "Credentials for {$userdn} failed in LdapServerTest.class.php";
         }
     } else {
         return LDAP_SUCCESS;
     }
     debug(t("LDAP bind failure for user %user. Error %errno: %error", array('%user' => $userdn, '%errno' => $ldap_errno, '%error' => $ldap_error)));
     return $ldap_errno;
 }
Exemplo n.º 12
0
 public function auth($username, PhutilOpaqueEnvelope $password)
 {
     if (strlen(trim($username)) == 0) {
         throw new Exception('Username can not be empty');
     }
     if (PhabricatorEnv::getEnvConfig('ldap.search-first')) {
         // To protect against people phishing for accounts we catch the
         // exception and present the default exception that would be presented
         // in the case of a failed bind.
         try {
             $user = $this->getUser($this->getUsernameAttribute(), $username);
             $username = $user[$this->getSearchAttribute()][0];
         } catch (PhabricatorLDAPUnknownUserException $e) {
             throw new Exception($this->invalidLDAPUserErrorMessage(self::LDAP_INVALID_CREDENTIALS, ldap_err2str(self::LDAP_INVALID_CREDENTIALS)));
         }
     }
     $conn = $this->getConnection();
     $activeDirectoryDomain = PhabricatorEnv::getEnvConfig('ldap.activedirectory_domain');
     if ($activeDirectoryDomain) {
         $dn = $username . '@' . $activeDirectoryDomain;
     } else {
         $dn = ldap_sprintf('%Q=%s,%Q', $this->getSearchAttribute(), $username, $this->getBaseDN());
     }
     // NOTE: It is very important we suppress any messages that occur here,
     // because it logs passwords if it reaches an error log of any sort.
     DarkConsoleErrorLogPluginAPI::enableDiscardMode();
     $result = @ldap_bind($conn, $dn, $password->openEnvelope());
     DarkConsoleErrorLogPluginAPI::disableDiscardMode();
     if (!$result) {
         throw new Exception($this->invalidLDAPUserErrorMessage(ldap_errno($conn), ldap_error($conn)));
     }
     $this->userData = $this->getUser($this->getSearchAttribute(), $username);
     return $this->userData;
 }
Exemplo n.º 13
0
 /**
  * return the errors for this object as html
  * 
  * @return string html listing the errors
  * @access public
  */
 function getHtmlErrors()
 {
     /*
     if ( file_exists(XOOPS_ROOT_PATH."/language/".$GLOBALS['xoopsConfig']['language']."/error.php") ) {
         include_once XOOPS_ROOT_PATH."/language/".$GLOBALS['xoopsConfig']['language']."/error.php";
     } else {
         include_once XOOPS_ROOT_PATH."/language/english/error.php";
     }
     */
     //$ret = '<h4>'._ERRORS.'</h4>';
     $ret = '<br>';
     if (!empty($this->_errors)) {
         foreach ($this->_errors as $errno => $errstr) {
             $msg = function_exists("ldap_err2str") ? ldap_err2str($errno) : '';
             $ret .= $msg . ' <br> ' . $errstr . '<br />';
         }
     } else {
         $ret .= _NONE . '<br />';
     }
     return $ret;
 }
Exemplo n.º 14
0
 /**
  * Convert LDAP error number into string error message.
  *
  * @param int $number
  *
  * @return string
  */
 public function err2Str($number)
 {
     return ldap_err2str($number);
 }
Exemplo n.º 15
0
 /**
  * Changes userpassword in LDAP
  *
  * Called when the user password is updated. It assumes it is
  * called by an admin or that you've otherwise checked the user's
  * credentials
  *
  * @param  object  $user        User table object
  * @param  string  $newpassword Plaintext password (not crypted/md5'ed)
  * @return boolean result
  *
  */
 function user_update_password($user, $newpassword)
 {
     global $USER;
     $result = false;
     $username = $user->username;
     $extusername = core_text::convert($username, 'utf-8', $this->config->ldapencoding);
     $extpassword = core_text::convert($newpassword, 'utf-8', $this->config->ldapencoding);
     switch ($this->config->passtype) {
         case 'md5':
             $extpassword = '******' . base64_encode(pack('H*', md5($extpassword)));
             break;
         case 'sha1':
             $extpassword = '******' . base64_encode(pack('H*', sha1($extpassword)));
             break;
         case 'plaintext':
         default:
             break;
             // plaintext
     }
     $ldapconnection = $this->ldap_connect();
     $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
     if (!$user_dn) {
         error_log($this->errorlogtag . get_string('nodnforusername', 'auth_ldap', $user->username));
         return false;
     }
     switch ($this->config->user_type) {
         case 'edir':
             // Change password
             $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
             if (!$result) {
                 error_log($this->errorlogtag . get_string('updatepasserror', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
             // Update password expiration time, grace logins count
             $search_attribs = array($this->config->expireattr, 'passwordExpirationInterval', 'loginGraceLimit');
             $sr = ldap_read($ldapconnection, $user_dn, '(objectClass=*)', $search_attribs);
             if ($sr) {
                 $entry = ldap_get_entries_moodle($ldapconnection, $sr);
                 $info = array_change_key_case($entry[0], CASE_LOWER);
                 $newattrs = array();
                 if (!empty($info[$this->config->expireattr][0])) {
                     // Set expiration time only if passwordExpirationInterval is defined
                     if (!empty($info['passwordexpirationinterval'][0])) {
                         $expirationtime = time() + $info['passwordexpirationinterval'][0];
                         $ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
                         $newattrs['passwordExpirationTime'] = $ldapexpirationtime;
                     }
                     // Set gracelogin count
                     if (!empty($info['logingracelimit'][0])) {
                         $newattrs['loginGraceRemaining'] = $info['logingracelimit'][0];
                     }
                     // Store attribute changes in LDAP
                     $result = ldap_modify($ldapconnection, $user_dn, $newattrs);
                     if (!$result) {
                         error_log($this->errorlogtag . get_string('updatepasserrorexpiregrace', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
                     }
                 }
             } else {
                 error_log($this->errorlogtag . get_string('updatepasserrorexpire', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
             break;
         case 'ad':
             // Passwords in Active Directory must be encoded as Unicode
             // strings (UCS-2 Little Endian format) and surrounded with
             // double quotes. See http://support.microsoft.com/?kbid=269190
             if (!function_exists('mb_convert_encoding')) {
                 error_log($this->errorlogtag . get_string('needmbstring', 'auth_ldap'));
                 return false;
             }
             $extpassword = mb_convert_encoding('"' . $extpassword . '"', "UCS-2LE", $this->config->ldapencoding);
             $result = ldap_modify($ldapconnection, $user_dn, array('unicodePwd' => $extpassword));
             if (!$result) {
                 error_log($this->errorlogtag . get_string('updatepasserror', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
             break;
         default:
             // Send LDAP the password in cleartext, it will md5 it itself
             $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
             if (!$result) {
                 error_log($this->errorlogtag . get_string('updatepasserror', 'auth_ldap', array('errno' => ldap_errno($ldapconnection), 'errstring' => ldap_err2str(ldap_errno($ldapconnection)))));
             }
     }
     $this->ldap_close();
     return $result;
 }
Exemplo n.º 16
0
 /**
  * Returns an LDAP option value.
  *
  * @param string $option Option to get.
  *
  * @return Horde_Ldap_Error|string Horde_Ldap_Error or option value
  * @throws Horde_Ldap_Exception
  */
 public function getOption($option)
 {
     if (!$this->_link) {
         throw new Horde_Ldap_Exception('No LDAP connection');
     }
     if (!defined($option)) {
         throw new Horde_Ldap_Exception('Unkown option requested');
     }
     if (@ldap_get_option($this->_link, constant($option), $value)) {
         return $value;
     }
     $err = @ldap_errno($this->_link);
     if ($err) {
         throw new Horde_Ldap_Exception(ldap_err2str($err), $err);
     }
     throw new Horde_Ldap_Exception('Unknown error');
 }
Exemplo n.º 17
0
 /**
  * Called with the error number of the last call if the error number is 0
  * there was no error otherwise it converts the error to a string and logs it as fatal
  *
  * @param INT $error
  * @return boolean
  */
 function loginError($error)
 {
     if (empty($error)) {
         return false;
     }
     $errorstr = ldap_err2str($error);
     // BEGIN SUGAR INT
     $_SESSION['login_error'] = $errorstr;
     /*
     // END SUGAR INT
     $_SESSION['login_error'] = translate('ERR_INVALID_PASSWORD', 'Users');
     // BEGIN SUGAR INT
     */
     // END SUGAR INT
     $GLOBALS['log']->fatal('[LDAP ERROR][' . $error . ']' . $errorstr);
     return true;
 }
Exemplo n.º 18
0
function GetAccountFromDistinguishedName($distinguised, $ldap_connection, $MemberAttribute, $dn)
{
    $dsn = array();
    $pattern = "(&(objectClass=user)(distinguishedName={$distinguised}))";
    $sr = @ldap_search($ldap_connection, $dn, $pattern, array());
    if (!$sr) {
        $error = ldap_err2str(ldap_err2str(ldap_errno($ldap_connection)));
        @ldap_close($ldap_connection);
        WLOG("Fatal: ldap_search -> {$pattern} in {$dn} FAILED {$error}");
        return array();
    }
    $result2 = @ldap_get_entries($ldap_connection, $sr);
    for ($i = 0; $i < $result2["count"]; $i++) {
        if (isset($result2[$i][$memberAttributeFromOPTIONS]["count"])) {
            for ($z = 0; $z < $result2[$i][$MemberAttribute]["count"]; $z++) {
                $dsn[$result2[$i][$MemberAttribute][$z]] = $result2[$i][$MemberAttribute][$z];
            }
        }
    }
    return $dsn;
}
Exemplo n.º 19
0
 /**
  * Return compound message of this exception.
  *
  * @return  string
  */
 public function compoundMessage()
 {
     return sprintf('Exception %s (LDAP errorcode #%d [%s]: %s)', nameof($this), $this->errorcode, ldap_err2str($this->errorcode), $this->message);
 }
Exemplo n.º 20
0
function CHECK_SQUID_EXTERNAL_LDAP()
{
    $sock = new sockets();
    $EXTERNAL_LDAP_AUTH_PARAMS = unserialize(base64_decode($sock->GET_INFO("SquidExternalAuth")));
    $ldap_server = $EXTERNAL_LDAP_AUTH_PARAMS["ldap_server"];
    $ldap_port = $EXTERNAL_LDAP_AUTH_PARAMS["ldap_port"];
    $ldap_suffix = $EXTERNAL_LDAP_AUTH_PARAMS["ldap_suffix"];
    $CONNECTION = @ldap_connect($ldap_server, $ldap_port);
    if (!$CONNECTION) {
        return "{failed_connect_ldap} {$ldap_server}:{$ldap_port}";
    }
    @ldap_set_option($CONNECTION, LDAP_OPT_PROTOCOL_VERSION, 3);
    @ldap_set_option($CONNECTION, LDAP_OPT_REFERRALS, 0);
    @ldap_set_option($CONNECTION, LDAP_OPT_PROTOCOL_VERSION, 3);
    // on passe le LDAP en version 3, necessaire pour travailler avec le AD
    @ldap_set_option($CONNECTION, LDAP_OPT_REFERRALS, 0);
    $userdn = $EXTERNAL_LDAP_AUTH_PARAMS["ldap_user"];
    $ldap_password = $EXTERNAL_LDAP_AUTH_PARAMS["ldap_password"];
    $BIND = @ldap_bind($CONNECTION, $userdn, $ldap_password);
    if (!$BIND) {
        $error = @ldap_err2str(@ldap_errno($CONNECTION));
        if (@ldap_get_option($CONNECTION, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
            $error = $error . " {$extended_error}";
        }
        @ldap_close($CONNECTION);
        return $error;
    }
    @ldap_close($CONNECTION);
}
Exemplo n.º 21
0
 private function doLoginAttempt($name, $pass, $remindMe, $language, $options)
 {
     try {
         /**
          * If invalid name or password, throw exception
          */
         if ($name === false || $pass === false) {
             throw new Exception(null, self::INVALID_USERNAME_EXECEPTION_CODE);
         }
         /**
          * check LDAP configuration in module's option table
          */
         if (!is_null($options) && is_array($options) && count($options) > 0) {
             // mandatory fields
             $mandatoryOptions = array('host' => 'Impostare l\'host LDAP', 'authdn' => 'Impostare il dn di autenticazione LDAP', 'basedn' => 'Impostare il dn di ricerca in LDAP', 'usertype' => 'Specificare il ruolo utente WISP');
             foreach ($mandatoryOptions as $optionName => $errorMessage) {
                 if (!array_key_exists($optionName, $options) || strlen($options[$optionName]) <= 0) {
                     $errorMessage = translateFN($errorMessage) . '<br/>(key=\'' . $optionName . '\' ' . translateFN('nelle opzioni') . ')';
                     throw new Exception($errorMessage);
                 }
             }
         } else {
             throw new Exception(translateFN('Impossibile caricare la configurazione LDAP'));
         }
         // connect to host
         $handle = ldap_connect($options['host']);
         // set options
         ldap_set_option($handle, LDAP_OPT_PROTOCOL_VERSION, 3);
         ldap_set_option($handle, LDAP_OPT_REFERRALS, 0);
         ldap_set_option($handle, LDAP_OPT_NETWORK_TIMEOUT, 30);
         /* 30 second timeout */
         // this will output a warning in the webserver log on failure
         $bind = ldap_bind($handle, 'uid=' . $name . ',' . $options['authdn'], $pass);
         if ($bind !== false) {
             /**
              * look if user is already in ADA DB
              */
             $userObj = $this->checkADAUser($name);
             if (!is_object($userObj) || !$userObj instanceof ADALoggableUser) {
                 /**
                  * If user is not in ADA DB, try loading his data from LDAP
                  */
                 $result = ldap_search($handle, $options['authdn'], "uid=" . $name);
                 /**
                  * If $results is false, throw an exception
                  */
                 if ($result !== false) {
                     $entries = ldap_get_entries($handle, $result);
                 } else {
                     throw new Exception(ldap_err2str(ldap_errno($handle)), ldap_errno($handle));
                 }
                 if ($entries !== false && is_array($entries) && count($entries) > 0) {
                     $entries = $entries[0];
                     /**
                      * If user uid is listed in the memberUid attributes
                      * for the basedn than it's safe to say that his type is $options['usertype']
                      */
                     if (!is_null($entries)) {
                         $namefilter = '(&(memberUid=' . $name . '))';
                         if (isset($options['filter']) && strlen($options['filter']) > 0) {
                             // extract filter up to last ')' character
                             $substr = substr($options['filter'], 0, strrpos($options['filter'], ')'));
                             // concatenate $namefilter to passed filter and restore the last ')'
                             $query = $substr . $namefilter . ')';
                         } else {
                             $query = $namefilter;
                         }
                         $groupres = ldap_search($handle, $options['basedn'], $query);
                         if ($groupres !== false) {
                             $groupentries = ldap_get_entries($handle, $groupres);
                         } else {
                             throw new Exception(ldap_err2str(ldap_errno($handle)), ldap_errno($handle));
                         }
                         if ($groupentries !== false && is_array($groupentries) && count($groupentries) > 0) {
                             if ($groupentries['count'] > 0) {
                                 // all went ok here: user has been found, user data has been loaded
                                 // and user memberUid was found on the passed basedn, create ADA user
                                 $userType = $options['usertype'];
                                 /**
                                  * build user array
                                  */
                                 $adaUser = array('nome' => $entries['givenname'][0], 'cognome' => $entries['sn'][0], 'email' => 'nobody', 'username' => $entries['uid'][0], 'tipo' => $options['usertype'], 'cap' => '', 'matricola' => '', 'avatar' => '', 'birthcity' => '');
                                 if (isset($handle) && !is_null($handle)) {
                                     ldap_unbind($handle);
                                 }
                                 return $this->addADAUser($adaUser);
                             }
                         }
                         return new Exception(translateFN('Utente non trovato nel dn fornito per') . ' ' . $options['name']);
                     }
                 }
             }
             // user not found in ADA
             /**
              * At this point, either the $userObj was already in
              * ADA DB or had just been created by the above code
              */
             if (is_object($userObj) && $userObj instanceof ADALoggableUser) {
                 return $userObj;
             }
         } else {
             throw new Exception(ldap_err2str(ldap_errno($handle)), ldap_errno($handle));
         }
     } catch (Exception $e) {
         if (!is_null($handle)) {
             ldap_unbind($handle);
         }
         // 'Invalid credentials' (code:49)  gets ADA's own message as text
         if ($e->getCode() == self::INVALID_USERNAME_EXECEPTION_CODE) {
             return new Exception(translateFN("Username  e/o password non valide"), self::INVALID_USERNAME_EXECEPTION_CODE);
         }
         return new Exception($e->getMessage() . ' ' . translateFN('di') . ' ' . $options['name']);
     }
 }
Exemplo n.º 22
0
 /**
  * Set the password of a user - This must be performed over SSL
  * 
  * @param string $username The username to modify
  * @param string $password The new password
  * @param bool $isGUID Is the username passed a GUID or a samAccountName
  * @return bool
  */
 public function password($username, $password, $isGUID = false)
 {
     if ($username === NULL) {
         return false;
     }
     if ($password === NULL) {
         return false;
     }
     if (!$this->adldap->getLdapBind()) {
         return false;
     }
     if (!$this->adldap->getUseSSL() && !$this->adldap->getUseTLS()) {
         throw new adLDAPException('SSL must be configured on your webserver and enabled in the class to set passwords.');
     }
     $userDn = $this->dn($username, $isGUID);
     if ($userDn === false) {
         return false;
     }
     $add = array();
     $add["unicodePwd"][0] = $this->encodePassword($password);
     $result = @ldap_mod_replace($this->adldap->getLdapConnection(), $userDn, $add);
     if ($result === false) {
         $err = ldap_errno($this->adldap->getLdapConnection());
         if ($err) {
             $msg = 'Error ' . $err . ': ' . ldap_err2str($err) . '.';
             if ($err == 53) {
                 $msg .= ' Your password might not match the password policy.';
             }
             throw new adLDAPException($msg);
         } else {
             return false;
         }
     }
     return true;
 }
Exemplo n.º 23
0
 /**
  * Get an LDAP option value
  *
  * @param string $option Option to get
  *
  * @access public
  * @return Net_LDAP2_Error|string Net_LDAP2_Error or option value
  */
 public function getOption($option)
 {
     if ($this->_link) {
         if (defined($option)) {
             if (@ldap_get_option($this->_link, constant($option), $value)) {
                 return $value;
             } else {
                 $err = @ldap_errno($this->_link);
                 if ($err) {
                     $msg = @ldap_err2str($err);
                 } else {
                     $err = NET_LDAP2_ERROR;
                     $msg = Net_LDAP2::errorMessage($err);
                 }
                 return $this->raiseError($msg, $err);
             }
         } else {
             $this->raiseError("Unkown Option requested");
         }
     } else {
         $this->raiseError("No LDAP connection");
     }
 }
 /**
  * Outputs debugging messages
  *
  * @access private
  * @param string Debugging Message
  * @param integer Line number
  */
 function _debug($msg = '', $line = 0)
 {
     if ($this->options['debug'] === true) {
         if ($msg == '' && $this->_isValidLink()) {
             $msg = 'LDAP_Error: ' . @ldap_err2str(@ldap_errno($this->_conn_id));
         }
         print "{$line}: {$msg} <br />";
     }
 }
Exemplo n.º 25
0
 public function errorMsg($type = NULL)
 {
     if ($type == 'ldap' && $this->connection) {
         return ldap_err2str(ldap_errno($this->connection));
     } elseif ($type == NULL) {
         return $this->_errorMsg;
     } else {
         return NULL;
     }
 }
Exemplo n.º 26
0
 function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE)
 {
     $userdn = $userdn != NULL ? $userdn : $this->binddn;
     $pass = $pass != NULL ? $pass : $this->bindpw;
     if (!isset($this->entries[$userdn])) {
         $ldap_errno = LDAP_NO_SUCH_OBJECT;
         // 0x20 or 32
         if (function_exists('ldap_err2str')) {
             $ldap_error = ldap_err2str($ldap_errno);
         } else {
             $ldap_error = "Failed to find {$userdn} in LdapServerTest.class.php";
         }
     } elseif (isset($this->entries[$userdn]['password'][0]) && $this->entries[$userdn]['password'][0] == $pass && $pass) {
         return LDAP_SUCCESS;
     } else {
         if (!$pass) {
             debug("Simpletest failure for {$userdn}.  No password submitted");
         }
         if (!isset($this->entries[$userdn]['password'][0])) {
             debug("Simpletest failure for {$userdn}.  No password in entry to test for bind");
             debug($this->entries[$userdn]);
         }
         $ldap_errno = LDAP_INVALID_CREDENTIALS;
         if (function_exists('ldap_err2str')) {
             $ldap_error = ldap_err2str($ldap_errno);
         } else {
             $ldap_error = "Credentials for {$userdn} failed in LdapServerTest.class.php";
         }
     }
     $watchdog_tokens = array('%user' => $userdn, '%errno' => $ldap_errno, '%error' => $ldap_error);
     watchdog('ldap', "LDAP bind failure for user %user. Error %errno: %error", $watchdog_tokens);
     return $ldap_errno;
 }
Exemplo n.º 27
0
/**
 * assigns the last LDAP error to the template
 */
function tpl_ldaperror($message = "")
{
    global $LDAP_CON;
    global $__LDAPERROR__;
    global $smarty;
    $errno = ldap_errno($LDAP_CON);
    if ($errno) {
        $__LDAPERROR__ .= ldap_err2str($errno);
        if (!empty($message)) {
            $__LDAPERROR__ .= "({$message})";
        } elseif ($errno == 4) {
            $__LDAPERROR__ .= "(You need to increase this limit in your server config)";
        }
        $__LDAPERROR__ .= '<br />';
    }
    $smarty->assign("LDAPERRORS", $__LDAPERROR__);
}
Exemplo n.º 28
0
function ConnectToAD($username, $password)
{
    $ChilliConf = unserialize(base64_decode(@file_get_contents("/etc/artica-postfix/settings/Daemons/ChilliConf")));
    if ($ChilliConf["EnableActiveDirectory"] == 0) {
        return false;
    }
    $AD_DOMAIN = $ChilliConf["AD_DOMAIN"];
    define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x32);
    events("ldap_connect({$ChilliConf["AD_SERVER"]},{$ChilliConf["AD_PORT"]})...");
    $cnx = @ldap_connect($ChilliConf["AD_SERVER"], $ChilliConf["AD_PORT"]);
    if (!$cnx) {
        events("Fatal: ldap_connect({$ChilliConf["AD_SERVER"]},{$ChilliConf["AD_PORT"]} ) Check your configuration...");
        @ldap_close();
        return false;
    }
    events("OK: ldap_connect({$ChilliConf["AD_SERVER"]},{$ChilliConf["AD_PORT"]} ) SUCCESS");
    @ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);
    @ldap_set_option($cnx, LDAP_OPT_REFERRALS, 0);
    @ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);
    // on passe le LDAP en version 3, necessaire pour travailler avec le AD
    @ldap_set_option($cnx, LDAP_OPT_REFERRALS, 0);
    events("Check ident {$username}@{$AD_DOMAIN} {$password}");
    $bind = @ldap_bind($cnx, "{$username}@{$AD_DOMAIN}", $password);
    if (!$bind) {
        $errn = ldap_errno($cnx);
        $error = "Error {$errn}: " . ldap_err2str($errn);
        if (@ldap_get_option($cnx, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
            $error = $error . " {$extended_error}";
        }
        events("{$error}");
        return false;
    }
    events("Active Directory session  SUCCESS");
    return true;
}
Exemplo n.º 29
0
 /**
  * Return the LDAP error message of the last LDAP command
  *
  * @param  int   $errorCode
  * @param  array $errorMessages
  * @return string
  */
 public function getLastError(&$errorCode = null, array &$errorMessages = null)
 {
     $errorCode = $this->getLastErrorCode();
     $errorMessages = array();
     /* The various error retrieval functions can return
      * different things so we just try to collect what we
      * can and eliminate dupes.
      */
     $estr1 = @ldap_error($this->_resource);
     if ($errorCode !== 0 && $estr1 === 'Success') {
         $estr1 = @ldap_err2str($errorCode);
     }
     if (!empty($estr1)) {
         $errorMessages[] = $estr1;
     }
     @ldap_get_option($this->_resource, LDAP_OPT_ERROR_STRING, $estr2);
     if (!empty($estr2) && !in_array($estr2, $errorMessages)) {
         $errorMessages[] = $estr2;
     }
     $message = '';
     if ($errorCode > 0) {
         $message = '0x' . dechex($errorCode) . ' ';
     } else {
         $message = '';
     }
     if (count($errorMessages) > 0) {
         $message .= '(' . implode('; ', $errorMessages) . ')';
     } else {
         $message .= '(no error message from LDAP)';
     }
     return $message;
 }
Exemplo n.º 30
0
 /**
  * Get the LDAP connection
  *
  * @param   integer  $debug
  * @return  mixed
  */
 public static function getLDO($debug = 0)
 {
     static $conn = false;
     if ($conn !== false) {
         return $conn;
     }
     $ldap_params = \Component::params('com_system');
     $acctman = $ldap_params->get('ldap_managerdn', 'cn=admin');
     $acctmanPW = $ldap_params->get('ldap_managerpw', '');
     $pldap = $ldap_params->get('ldap_primary', 'ldap://localhost');
     $negotiate_tls = $ldap_params->get('ldap_tls', 0);
     $port = '389';
     if (!is_numeric($port)) {
         $port = '389';
         $pattern = "/^\\s*(ldap[s]{0,1}:\\/\\/|)([^:]*)(\\:(\\d+)|)\\s*\$/";
         if (preg_match($pattern, $pldap, $matches)) {
             $pldap = $matches[2];
             if ($matches[1] == 'ldaps://') {
                 $negotiate_tls = false;
             }
             if (isset($matches[4]) && is_numeric($matches[4])) {
                 $port = $matches[4];
             }
         }
     }
     $conn = ldap_connect($pldap, $port);
     if ($conn === false) {
         if ($debug) {
             \Log::debug("getLDO(): ldap_connect({$pldap},{$port}) failed. [" . posix_getpid() . "] " . ldap_error($conn));
         }
         return false;
     }
     if ($debug) {
         \Log::debug("getLDO(): ldap_connect({$pldap},{$port}) success. ");
     }
     if (ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3) == false) {
         if ($debug) {
             \Log::debug("getLDO(): ldap_set_option(LDAP_OPT_PROTOCOL_VERSION, 3) failed: " . ldap_error($conn));
         }
         $conn = false;
         return false;
     }
     if ($debug) {
         \Log::debug("getLDO(): ldap_set_option(LDAP_OPT_PROTOCOL_VERSION, 3) success.");
     }
     if (ldap_set_option($conn, LDAP_OPT_RESTART, 1) == false) {
         if ($debug) {
             \Log::debug("getLDO(): ldap_set_option(LDAP_OPT_RESTART, 1) failed: " . ldap_error($conn));
         }
         $conn = false;
         return false;
     }
     if ($debug) {
         \Log::debug("getLDO(): ldap_set_option(LDAP_OPT_RESTART, 1) success.");
     }
     if (!ldap_set_option($conn, LDAP_OPT_REFERRALS, false)) {
         if ($debug) {
             \Log::debug("getLDO(): ldap_set_option(LDAP_OPT_REFERRALS, 0) failed: " . ldap_error($conn));
         }
         $conn = false;
         return false;
     }
     if ($debug) {
         \Log::debug("getLDO(): ldap_set_option(LDAP_OPT_REFERRALS, 0) success.");
     }
     if ($negotiate_tls) {
         if (!ldap_start_tls($conn)) {
             if ($debug) {
                 \Log::debug("getLDO(): ldap_start_tls() failed: " . ldap_error($conn));
             }
             $conn = false;
             return false;
         }
         if ($debug) {
             \Log::debug("getLDO(): ldap_start_tls() success.");
         }
     }
     if (ldap_bind($conn, $acctman, $acctmanPW) == false) {
         $err = ldap_errno($conn);
         $errstr = ldap_error($conn);
         $errstr2 = ldap_err2str($err);
         if ($debug) {
             \Log::debug("getLDO(): ldap_bind({$acctman}) failed. [" . posix_getpid() . "] " . $errstr);
         }
         $conn = false;
         return false;
     }
     if ($debug) {
         \Log::debug("getLDO(): ldap_bind() success.");
     }
     return $conn;
 }