function ldap_authenticate($user, $pass)
{
    // Global variables
    global $ldap_base_DN, $ldap_server, $template, $admin_users, $ldap_user_cn;
    // Connect to the LDAP server
    $conn = ldap_connect($ldap_server) or die("Cannot connect");
    ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
    // Bind anonymously, query the server for the user, and error if it can't be found
    if (!($bind = ldap_bind($conn))) {
        $template['message'] = "<p>Anonymous bind failed.</p>";
        return;
    }
    // Do a search for the username and get the DN - this is easier than manually constructing it
    if (!($search = ldap_search($conn, $ldap_base_DN, "{$ldap_user_cn}={$user}"))) {
        $template['message'] = "<p><strong>Error:</strong> Could not find the username.</p>";
        return;
    }
    // If there isn't only one row.
    if (ldap_count_entries($conn, $search) != 1) {
        $template['message'] = "<p>There was an error processing the username, or it cannot be found.</p>";
        return;
    }
    // Extract the entries, and bind with the user's full DN, then unset the password for security
    $entries = @ldap_get_entries($conn, $search);
    $bind_auth = @ldap_bind($conn, $entries[0]['dn'], $pass);
    unset($pass);
    // If we have a successful bind, add the relevant session information
    if ($bind_auth) {
        $_SESSION['admin'] = in_array($user, $admin_users);
        $_SESSION['username'] = $user;
        header('Location: index.php');
    } else {
        $template['message'] = "<p><strong>Login failed.</strong> Please try again.</p>";
    }
}
Example #2
1
 /**
  * method to connect to the ldap server
  */
 public function connect()
 {
     $this->connection = ldap_connect($this->LDAPServer);
     ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
     $ldap_bind = ldap_bind($this->connection, $this->LDAPDomain . "\\" . $this->LDAPUser, $this->LDAPPassword);
 }
Example #3
0
 function login($username, $password)
 {
     global $_SESSION;
     // Check for LDAP functions
     if (!function_exists('ldap_connect')) {
         $ex = 'LDAP support is not enabled in your PHP configuration.';
         if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
             ob_start();
             phpinfo(INFO_GENERAL);
             $phpinfo = ob_get_contents();
             ob_end_clean();
             preg_match('/Loaded Configuration File <\\/td><td.*?>(.*?)\\s*</', $phpinfo, $phpinfo);
             $ex .= ' You probably just need to uncomment the line ;extension=php_ldap.dll in php.ini' . (count($phpinfo) > 1 ? ' (' . trim($phpinfo[1]) . ')' : '') . ' by removing the ";" and restart your web server.';
         } else {
             if (strtolower(substr(PHP_OS, 0, 5)) == 'Linux') {
                 $ex .= ' You probably need to install the php5-ldap (or similar depending on your distribution) package.';
             }
         }
         throw new Exception($ex);
     }
     $auth = ldap_connect($this->config['host']);
     if (!$auth) {
         return false;
     }
     ldap_set_option($auth, LDAP_OPT_PROTOCOL_VERSION, 3);
     if (!@ldap_bind($auth, sprintf($this->config['bind_dn'], $username), $password)) {
         return false;
     }
     $_SESSION['valid'] = true;
     $_SESSION['user'] = $username;
     $_SESSION['admin'] = !$this->config['adminUser'] || $_SESSION['user'] == $this->config['adminUser'];
     $_SESSION['authCheckHeartbeat'] = time();
 }
Example #4
0
 public function getAllUsers()
 {
     // Settings for LDAP
     if ($this->container->hasParameter('ldap_host')) {
         $ldapHostname = $this->container->getParameter("ldap_host");
         $ldapPort = $this->container->getParameter("ldap_port");
         $ldapVersion = $this->container->getParameter("ldap_version");
         $baseDn = $this->container->getParameter("ldap_user_base_dn");
         $nameAttribute = $this->container->getParameter("ldap_user_name_attribute");
         $filter = "(" . $nameAttribute . "=*)";
         $connection = @ldap_connect($ldapHostname, $ldapPort);
         ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldapVersion);
         $ldapListRequest = ldap_list($connection, $baseDn, $filter);
         // or throw exeption('Unable to list. LdapError: ' . ldap_error($ldapConnection));
         $ldapUserList = ldap_get_entries($connection, $ldapListRequest);
     }
     // Settings for local user database
     $repo = $this->getDoctrine()->getRepository('FOMUserBundle:User');
     $users = $repo->findAll();
     $all = array();
     if ($this->container->hasParameter('ldap_host')) {
         // Add Users from LDAP
         foreach ($ldapUserList as $ldapUser) {
             $user = new \stdClass();
             $user->getUsername = $ldapUser[$nameAttribute][0];
             $all[] = $user;
         }
     }
     // Add Mapbenderusers from database
     foreach ($users as $user) {
         $all[] = $user;
     }
     return $all;
 }
Example #5
0
function login_ad($user_, $pass_, $tipo_)
{
    //Comienzo la conexión al servidor para tomar los datos de active directory
    $host = get_config('host');
    $puerto = get_config('puerto');
    $filter = "sAMAccountName=" . $user_ . "*";
    $attr = array("displayname", "mail", "givenname", "sn", "useraccountcontrol");
    $dn = get_config('dn');
    $conex = ldap_connect($host, $puerto) or die("No ha sido posible conectarse al servidor");
    if (!ldap_set_option($conex, LDAP_OPT_PROTOCOL_VERSION, 3)) {
        echo "<br>Failed to set protocol version to 3";
    }
    if ($conex) {
        $dominio = get_config("dominio");
        $r = @ldap_bind($conex, $user_ . $dominio, $pass_);
        $existe = get_perfil($user_, $tipo_);
        if ($r && count($existe) > 0) {
            //LOGIN CORRECTO
            $result = ldap_search($conex, $dn, $filter, $attr);
            $entries = ldap_get_entries($conex, $result);
            for ($i = 0; $i < $entries["count"]; $i++) {
                $nombre = fix_data(utf8_decode($entries[$i]["givenname"][0]));
                $apellidos = fix_data(utf8_decode($entries[$i]["sn"][0]));
                $email = fix_data($entries[$i]["mail"][0]);
                //Acutalizar información desde AD en la tabla de empleados
                $s_ = "update empleados set nombre='{$nombre}', apellidos='{$apellidos}', mail='{$email}' where id='{$existe['id']}'";
                $r_ = mysql_query($s_);
                session_name("loginUsuario");
                session_start();
                $_SESSION['NAME'] = $nombre . " " . $apellidos;
                $_SESSION['USER'] = $user_;
                $_SESSION['IDEMP'] = $existe['id'];
                $_SESSION['AUSENCIA'] = get_ausencia($existe['id']);
                $_SESSION['DEPTO'] = $existe['depto'];
                $_SESSION['TYPE'] = $tipo_;
            }
            switch ($tipo_) {
                case "administrador":
                    header("Location: admin/inicio.php");
                    break;
                case "capturista":
                    header("Location: capturista/inicio.php");
                    break;
                case "autorizador":
                    header("Location: autorizador/scrap_firmar.php");
                    break;
                case "reportes":
                    header("Location: reportes/rep_general.php?op=listado");
                    break;
            }
        } else {
            echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=index.php?error=2&user_={$user_}&tipo_={$tipo_}\">";
            exit;
        }
        ldap_close($conex);
    } else {
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=index.php?error=3&user_={$user_}&tipo_={$tipo_}\">";
        exit;
    }
}
Example #6
0
 /**
  * Initiate LDAP connection.
  *
  * Not done in __construct(), only when a read or write action is
  * necessary.
  */
 protected function _connect()
 {
     if ($this->_ds) {
         return;
     }
     if (!($this->_ds = @ldap_connect($this->_params['server'], $this->_params['port']))) {
         throw new Turba_Exception(_("Connection failure"));
     }
     /* Set the LDAP protocol version. */
     if (!empty($this->_params['version'])) {
         @ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, $this->_params['version']);
     }
     /* Set the LDAP deref option for dereferencing aliases. */
     if (!empty($this->_params['deref'])) {
         @ldap_set_option($this->_ds, LDAP_OPT_DEREF, $this->_params['deref']);
     }
     /* Set the LDAP referrals. */
     if (!empty($this->_params['referrals'])) {
         @ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, $this->_params['referrals']);
     }
     /* Start TLS if we're using it. */
     if (!empty($this->_params['tls']) && !@ldap_start_tls($this->_ds)) {
         throw new Turba_Exception(sprintf(_("STARTTLS failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
     }
     /* Bind to the server. */
     if (isset($this->_params['bind_dn']) && isset($this->_params['bind_password'])) {
         $error = !@ldap_bind($this->_ds, $this->_params['bind_dn'], $this->_params['bind_password']);
     } else {
         $error = !@ldap_bind($this->_ds);
     }
     if ($error) {
         throw new Turba_Exception(sprintf(_("Bind failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
     }
 }
Example #7
0
 public function connect()
 {
     // connection already established
     if ($this->ds) {
         return true;
     }
     $this->bound = 0;
     if (!($this->ds = ldap_connect($this->cnf['host'], $this->cnf['port']))) {
         error('LDAP: couldn\'t connect to LDAP server.');
         return false;
     }
     // set protocol version and dependend options
     if ($this->cnf['version']) {
         if (!ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, $this->cnf['version'])) {
             error('Setting LDAP Protocol version ' . $this->cnf['version'] . ' failed.');
         } else {
             // use TLS (needs version 3)
             if (isset($this->cnf['starttls']) && !ldap_start_tls($this->ds)) {
                 error('Starting TLS failed.');
             }
             // needs version 3
             if (!zbx_empty($this->cnf['referrals']) && !ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $this->cnf['referrals'])) {
                 error('Setting LDAP referrals to off failed.');
             }
         }
     }
     // set deref mode
     if (isset($this->cnf['deref']) && !ldap_set_option($this->ds, LDAP_OPT_DEREF, $this->cnf['deref'])) {
         error('Setting LDAP Deref mode ' . $this->cnf['deref'] . ' failed.');
     }
     return true;
 }
function get_ldap_members($group, $user, $password)
{
    global $ldap_host;
    global $ldap_dn;
    $LDAPFieldsToFind = array("member");
    print "{$ldap_host} {$ldap_dn}\n";
    $ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
    // OPTIONS TO AD
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    ldap_bind($ldap, $user, $password) or die("Could not bind to LDAP");
    //check if group is just a name or an ldap string
    $group_cn = preg_match("/cn=/i", $group) ? $group : "cn={$group}";
    $results = ldap_search($ldap, $ldap_dn, $group_cn, $LDAPFieldsToFind);
    $member_list = ldap_get_entries($ldap, $results);
    $group_member_details = array();
    if (is_array($member_list[0])) {
        foreach ($member_list[0] as $list) {
            if (is_array($list)) {
                foreach ($list as $member) {
                    $member_dn = explode_dn($member);
                    $member_cn = str_replace("CN=", "", $member_dn[0]);
                    $member_search = ldap_search($ldap, $ldap_dn, "(CN=" . $member_cn . ")");
                    $member_details = ldap_get_entries($ldap, $member_search);
                    $group_member_details[] = array($member_details[0]['samaccountname'][0], $member_details[0]['displayname'][0], $member_details[0]['useraccountcontrol'][0]);
                }
            }
        }
    }
    ldap_close($ldap);
    array_shift($group_member_details);
    return $group_member_details;
    ldap_unbind($ldap);
}
Example #9
0
 private function setoptions($handle, $configuration)
 {
     ldap_set_option($handle, LDAP_OPT_PROTOCOL_VERSION, $configuration['protocol']);
     ldap_set_option($handle, LDAP_OPT_REFERRALS, $configuration['referrals']);
     ldap_set_option($handle, LDAP_OPT_TIMELIMIT, $configuration['timelimit']);
     ldap_set_option($handle, LDAP_OPT_NETWORK_TIMEOUT, $configuration['timeout']);
 }
Example #10
0
function LDAPLogin($server = "mydomain.local", $username, $password, $domain = "mydomain", $dc = "dc=mydomain,dc=local")
{
    // https://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/
    $ldap = ldap_connect("ldap://{$server}");
    $ldaprdn = "{$domain}\\{$username}";
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    $bind = @ldap_bind($ldap, $ldaprdn, $password);
    if ($bind) {
        $filter = "(sAMAccountName={$username})";
        $result = ldap_search($ldap, $dc, $filter);
        ldap_sort($ldap, $result, "sn");
        $info = ldap_get_entries($ldap, $result);
        if (!isset($info[0]["mail"][0])) {
            Log::createLog("danger", "ldap", "Unable to query LDAP, check base settings.");
            return null;
        }
        $data = array();
        $data["email"] = $info[0]["mail"][0];
        $data["lastname"] = $info[0]["sn"][0];
        $data["firstname"] = $info[0]["givenname"][0];
        @ldap_close($ldap);
        return $data;
    } else {
        Log::createLog("danger", "ldap", "Error: " . ldap_error($ldap));
    }
    return null;
}
Example #11
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!");
     }
 }
Example #12
0
 private function bind($authenticated = false)
 {
     if ($this->connected) {
         if ($authenticated && !$this->authenticated) {
             ldap_bind($this->connection, $this->config['username'] . ',' . $this->config['dn'], $this->config['password']);
         }
         return;
     }
     ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
     try {
         $connection = ldap_connect($this->config['host']);
         // Change protocol
         ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
         ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
         if ($authenticated) {
             ldap_bind($connection, $this->config['username'] . ',' . $this->config['dn'], $this->config['password']);
         }
         // Start TLS
         // ldap_start_tls($connection);
     } catch (Exception $e) {
         print_r($e);
         return;
     }
     $this->connected = true;
     $this->connection = $connection;
 }
Example #13
0
 private function connect()
 {
     $port = isset($this->params['client']['port']) ? $this->params['client']['port'] : '389';
     $ress = @ldap_connect($this->params['client']['host'], $port);
     if (isset($this->params['client']['version']) && $this->params['client']['version'] !== null) {
         ldap_set_option($ress, LDAP_OPT_PROTOCOL_VERSION, $this->params['client']['version']);
     }
     if (isset($this->params['client']['referrals_enabled']) && $this->params['client']['referrals_enabled'] !== null) {
         ldap_set_option($ress, LDAP_OPT_REFERRALS, $this->params['client']['referrals_enabled']);
     }
     if (isset($this->params['client']['username']) && $this->params['client']['version'] !== null) {
         if (!isset($this->params['client']['password'])) {
             throw new \Exception('You must uncomment password key');
         }
         $bindress = @ldap_bind($ress, $this->params['client']['username'], $this->params['client']['password']);
         if (!$bindress) {
             throw new \Exception('The credentials you have configured are not valid');
         }
     } else {
         $bindress = @ldap_bind($ress);
         if (!$bindress) {
             throw new \Exception('Unable to connect Ldap');
         }
     }
     $this->_ress = $ress;
     return $this;
 }
Example #14
0
 /**
  * Connection to the database
  *
  */
 public function __construct()
 {
     $this->domain = $domain;
     parent::__construct();
     require FRAMEWORK . DS . 'conf' . DS . 'datastore.php';
     $config = $datastore[$this->datastore];
     if (!isset(self::$connection[$this->datastore])) {
         self::$connection[$this->datastore] = @ldap_connect($config['protocol'] . $config['domain']);
         if (!self::$connection[$this->datastore]) {
             throw new connectException('Could not connect to the Active Directory.');
         }
         ldap_set_option(self::$connection[$this->datastore], LDAP_OPT_REFERRALS, 0);
         ldap_set_option(self::$connection[$this->datastore], LDAP_OPT_PROTOCOL_VERSION, 3);
         if (!@ldap_bind(self::$connection[$this->datastore], $config['user'] . '@' . $config['domain'], $config['password'])) {
             throw new connectException('Could not bind to the Active Directory.');
         }
     }
     $this->con =& self::$connection[$this->datastore];
     $this->dn = $config['dn'];
     $config2 = $datastore[$this->datastore2];
     if (!isset(self::$connection[$this->datastore2])) {
         self::$connection[$this->datastore2] = @ldap_connect($config2['protocol'] . $config2['domain']);
         if (!self::$connection[$this->datastore2]) {
             throw new connectException('Could not connect to the Active Directory.');
         }
         ldap_set_option(self::$connection[$this->datastore2], LDAP_OPT_REFERRALS, 0);
         ldap_set_option(self::$connection[$this->datastore2], LDAP_OPT_PROTOCOL_VERSION, 3);
         if (!@ldap_bind(self::$connection[$this->datastore2], $config2['user'] . '@' . $config2['domain'], $config2['password'])) {
             throw new connectException('Could not bind to the Active Directory.');
         }
     }
     $this->con2 =& self::$connection[$this->datastore2];
     $this->dn2 = $config2['dn'];
     $this->attributes = array_keys($this->mapping);
 }
Example #15
0
 /**
  * Constructor
  */
 function __construct()
 {
     $this->ds = ldap_connect($this->host);
     ldap_set_option($this->ds, LDAP_OPT_REFERRALS, 0);
     ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_bind($this->ds, $this->user, $this->pass);
 }
Example #16
0
 private static function getADConnection($username = null, $password = null)
 {
     if (!function_exists("ldap_connect")) {
         return null;
     }
     $LD = LoginData::get("ADServerUserPass");
     if ($LD == null) {
         return null;
     }
     $adServer = "ldap://" . $LD->A("server");
     $ex = explode("@", $LD->A("benutzername"));
     if ($username == null) {
         $username = $LD->A("benutzername");
     } else {
         $username = $username . "@" . $ex[1];
     }
     if ($password == null) {
         $password = $LD->A("passwort");
     }
     $ldap = ldap_connect($adServer);
     ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
     $bind = ldap_bind($ldap, $username, $password);
     if (!$bind) {
         throw new Exception("Keine Verbindung zu AD-Server");
     }
     return $ldap;
 }
Example #17
0
function checkAdLoginAuth($user_id, $login_passwd)
{
    //接続開始
    $ldap_conn = ldap_connect(LDAP_HOST_1, LDAP_PORT);
    if (!$ldap_conn) {
        $ldap_conn = ldap_connect("ldaps://" . LDAP_HOST_2);
    } else {
        print_r("OK" . PHP_EOL);
    }
    if (!$ldap_conn) {
        Debug_Trace("接続失敗");
        return false;
    }
    if ($ldap_conn) {
        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
        $ldap_bind = ldap_bind($ldap_conn, "CN=" . $user_id . "," . LDAP_DN, $login_passwd);
        if ($ldap_bind) {
            Debug_Trace("ADの認証に成功しました", 3);
            return true;
        } else {
            Debug_Trace("ADの認証に失敗しました", 3);
            Debug_Trace($user_id, 3);
            return false;
        }
    } else {
        Debug_Trace('ADサーバへの接続に失敗しました');
        return false;
    }
    ldap_close($ldap_conn);
    return true;
}
Example #18
0
function ldap_init()
{
    global $ds, $config;
    if (!is_resource($ds)) {
        print_debug("LDAP[Connecting to " . implode(",", $config['auth_ldap_server']) . "]");
        $ds = @ldap_connect(implode(",", $config['auth_ldap_server']), $config['auth_ldap_port']);
        print_debug("LDAP[Connected]");
        if ($config['auth_ldap_starttls'] && ($config['auth_ldap_starttls'] == 'optional' || $config['auth_ldap_starttls'] == 'require')) {
            $tls = ldap_start_tls($ds);
            if ($config['auth_ldap_starttls'] == 'require' && $tls == FALSE) {
                session_logout();
                print_error("Fatal error: LDAP TLS required but not successfully negotiated [" . ldap_error($ds) . "]");
                exit;
            }
        }
        if ($config['auth_ldap_referrals']) {
            ldap_set_option($ds, LDAP_OPT_REFERRALS, $config['auth_ldap_referrals']);
            print_debug("LDAP[Referrals][Set to " . $config['auth_ldap_referrals'] . "]");
        } else {
            ldap_set_option($ds, LDAP_OPT_REFERRALS, FALSE);
            print_debug("LDAP[Referrals][Disabled]");
        }
        if ($config['auth_ldap_version']) {
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $config['auth_ldap_version']);
            print_debug("LDAP[Version][Set to " . $config['auth_ldap_version'] . "]");
        }
    }
}
Example #19
0
function ldap_connect_bind($p_binddn = '', $p_password = '')
{
    $t_ldap_server = config_get('ldap_server');
    $t_ldap_port = config_get('ldap_port');
    if (!extension_loaded('ldap')) {
        trigger_error(ERROR_LDAP_EXTENSION_NOT_LOADED, ERROR);
    }
    $t_ds = @ldap_connect($t_ldap_server, $t_ldap_port);
    if ($t_ds > 0) {
        $t_protocol_version = config_get('ldap_protocol_version');
        if ($t_protocol_version > 0) {
            ldap_set_option($t_ds, LDAP_OPT_PROTOCOL_VERSION, $t_protocol_version);
        }
        # If no Bind DN and Password is set, attempt to login as the configured
        #  Bind DN.
        if (is_blank($p_binddn) && is_blank($p_password)) {
            $p_binddn = config_get('ldap_bind_dn', '');
            $p_password = config_get('ldap_bind_passwd', '');
        }
        if (!is_blank($p_binddn) && !is_blank($p_password)) {
            $t_br = @ldap_bind($t_ds, $p_binddn, $p_password);
        } else {
            # Either the Bind DN or the Password are empty, so attempt an anonymous bind.
            $t_br = @ldap_bind($t_ds);
        }
        if (!$t_br) {
            trigger_error(ERROR_LDAP_AUTH_FAILED, ERROR);
        }
    } else {
        trigger_error(ERROR_LDAP_SERVER_CONNECT_FAILED, ERROR);
    }
    return $t_ds;
}
Example #20
0
 public function lookupUser($credentials)
 {
     $username = $credentials['username'];
     $password = $credentials['password'];
     $this->log('Ldap: looking up user "' . $username . '" in LDAP server ');
     $sourceConfig = $this->source;
     $server = parse_url($sourceConfig['url']);
     if (empty($server['host'])) {
         return false;
         // oops
     }
     $connect = ldap_connect($server['host'], empty($server['port']) ? 389 : $server['port']);
     ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
     //$connect=ldap_connect($server['host']);
     $this->log('Connected');
     if (!$connect) {
         throw new PHPDS_exception('Unable to connect to the LDAP server');
     }
     if ($sourceConfig['namePattern']) {
         $username = PU_sprintfn($sourceConfig['namePattern'], array($username));
     }
     if (!@ldap_bind($connect, $username, $password)) {
         return false;
         // if we can't bind it's likely the user is unknown or the password is wrong
     }
     $this->log('Bound');
     return true;
 }
Example #21
0
function ldap_getCnx($server_id = null)
{
    global $ldap_server;
    if (is_null($server_id)) {
        return False;
    } else {
        if ($ldap_server[$server_id]['protoversion'] == 'ldapv3' && $ldap_server[$server_id]['encrypt'] != 'ldaps') {
            $ds = ldap_connect($ldap_server[$server_id]['server'], $ldap_server[$server_id]['port']);
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
            if (!$ldap_server[$server_id]['referrals']) {
                ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
            }
            if ($ldap_server[$server_id]['encrypt'] == 'start-tls') {
                ldap_start_tls($ds);
            }
        } elseif ($ldap_server[$server_id]['protoversion'] == 'ldapv2') {
            if ($ldap_server[$server_id]['encrypt'] == 'ldaps') {
                $ds = ldap_connect("ldaps://" . $ldap_server[$server_id]['server'], $ldap_server[$server_id]['port']);
            } else {
                $ds = ldap_connect($ldap_server[$server_id]['server'], $ldap_server[$server_id]['port']);
            }
            if (!$ldap_server[$server_id]['referrals']) {
                ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
            }
        }
        return $ds;
    }
}
Example #22
0
 /**
  * ->_init()
  * connect and bind to the LDAP host
  */
 function _init()
 {
     if ($this->_ldap = ldap_connect(LDAP_AUTH_HOST)) {
         // must be a valid LDAP server!
         global $LDAP_SET_OPTION;
         if (!empty($LDAP_SET_OPTION)) {
             foreach ($LDAP_SET_OPTION as $key => $value) {
                 //if (is_string($key) and defined($key))
                 //    $key = constant($key);
                 ldap_set_option($this->_ldap, $key, $value);
             }
         }
         if (LDAP_AUTH_USER) {
             if (LDAP_AUTH_PASSWORD) {
                 // Windows Active Directory Server is strict
                 $r = ldap_bind($this->_ldap, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD);
             } else {
                 $r = ldap_bind($this->_ldap, LDAP_AUTH_USER);
             }
         } else {
             $r = true;
         }
         // anonymous bind allowed
         if (!$r) {
             $this->_free();
             trigger_error(sprintf(_("Unable to bind LDAP server %s using %s %s"), LDAP_AUTH_HOST, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD), E_USER_WARNING);
             return false;
         }
         return $this->_ldap;
     } else {
         return false;
     }
 }
Example #23
0
function authenticate($username, $password)
{
    global $config, $ldap_connection;
    if ($username && $ldap_connection) {
        if ($config['auth_ldap_version']) {
            ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, $config['auth_ldap_version']);
        }
        if (ldap_bind($ldap_connection, $config['auth_ldap_prefix'] . $username . $config['auth_ldap_suffix'], $password)) {
            if (!$config['auth_ldap_group']) {
                return 1;
            } else {
                $ldap_groups = get_group_list();
                foreach ($ldap_groups as $ldap_group) {
                    $ldap_comparison = ldap_compare($ldap_connection, $ldap_group, $config['auth_ldap_groupmemberattr'], get_membername($username));
                    if ($ldap_comparison === true) {
                        return 1;
                    }
                }
            }
        } else {
            echo ldap_error($ldap_connection);
        }
    } else {
        // FIXME return a warning that LDAP couldn't connect?
    }
    return 0;
}
Example #24
0
 /**
  * Makes a connection to LDAP using the settings in Admin > Settings.
  *
  * @author [A. Gianotto] [<*****@*****.**>]
  * @since [v3.0]
  * @return connection
  */
 public static function connectToLdap()
 {
     $ldap_host = Setting::getSettings()->ldap_server;
     $ldap_version = Setting::getSettings()->ldap_version;
     $ldap_server_cert_ignore = Setting::getSettings()->ldap_server_cert_ignore;
     $ldap_use_tls = Setting::getSettings()->ldap_tls;
     // If we are ignoring the SSL cert we need to setup the environment variable
     // before we create the connection
     if ($ldap_server_cert_ignore == '1') {
         putenv('LDAPTLS_REQCERT=never');
     }
     // If the user specifies where CA Certs are, make sure to use them
     if (env("LDAPTLS_CACERT")) {
         putenv("LDAPTLS_CACERT=" . env("LDAPTLS_CACERT"));
     }
     $connection = @ldap_connect($ldap_host);
     if (!$connection) {
         throw new Exception('Could not connect to LDAP server at ' . $ldap_host . '. Please check your LDAP server name and port number in your settings.');
     }
     // Needed for AD
     ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
     ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);
     if ($ldap_use_tls == '1') {
         ldap_start_tls($connection);
     }
     return $connection;
 }
Example #25
0
 /**
  * Initializes the backend to perform the search
  * Connects to the LDAP server using the values from the configuration
  *
  *
  * @access public
  * @return
  * @throws StatusException
  */
 public function BackendSearchLDAP()
 {
     if (!function_exists("ldap_connect")) {
         throw new StatusException("BackendSearchLDAP(): php-ldap is not installed. Search aborted.", SYNC_SEARCHSTATUS_STORE_SERVERERROR, null, LOGLEVEL_FATAL);
     }
     // connect to LDAP
     $this->connection = @ldap_connect(LDAP_HOST, LDAP_PORT);
     @ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
     // Authenticate
     if (constant('ANONYMOUS_BIND') === true) {
         if (!@ldap_bind($this->connection)) {
             $this->connection = false;
             throw new StatusException("BackendSearchLDAP(): Could not bind anonymously to server! Search aborted.", SYNC_SEARCHSTATUS_STORE_CONNECTIONFAILED, null, LOGLEVEL_ERROR);
         }
     } else {
         if (constant('LDAP_BIND_USER') != "") {
             if (!@ldap_bind($this->connection, LDAP_BIND_USER, LDAP_BIND_PASSWORD)) {
                 $this->connection = false;
                 throw new StatusException(sprintf("BackendSearchLDAP(): Could not bind to server with user '%s' and specified password! Search aborted.", LDAP_BIND_USER), SYNC_SEARCHSTATUS_STORE_ACCESSDENIED, null, LOGLEVEL_ERROR);
             }
         } else {
             // it would be possible to use the users login and password to authenticate on the LDAP server
             // the main $backend has to keep these values so they could be used here
             $this->connection = false;
             throw new StatusException("BackendSearchLDAP(): neither anonymous nor default bind enabled. Other options not implemented.", SYNC_SEARCHSTATUS_STORE_CONNECTIONFAILED, null, LOGLEVEL_ERROR);
         }
     }
 }
 /**
  * Logs the user in to the TMT through LDAP
  *
  * Expects the netId and password fields to be set in the request
  */
 public function ldap($params)
 {
     session_start();
     $netId = isset($params['request']['netId']) ? $params['request']['netId'] : null;
     $password = isset($params['request']['password']) ? $params['request']['password'] : null;
     if ($netId == null || $password == null) {
         session_destroy();
         header('Location: /landing');
         exit;
     }
     $link = \ldap_connect(getenv("LDAPURL"), 389);
     if ($link) {
         \ldap_set_option($link, LDAP_OPT_SIZELIMIT, 2);
         $authenticated = @\ldap_bind($link, 'uid=' . $netId . ',ou=People,o=byu.edu', $password);
         if ($authenticated) {
             $_SESSION['user'] = $netId;
             $_SESSION['ldap'] = true;
             header('Location: /');
             exit;
         } else {
             session_destroy();
             $this->user['netId'] = null;
             $this->render("helpers/loginFail");
             exit;
         }
     } else {
         // Unable to connect to LDAP, return to landing page
         session_destroy();
         header('Location: /landing');
         exit;
     }
 }
Example #27
0
 protected function open()
 {
     $bind = \ldap_connect($this->ldap_server);
     \ldap_set_option($this->bind, LDAP_OPT_PROTOCOL_VERSION, 3);
     \ldap_bind($bind, $this->admin_user . ',' . $this->base_dn, $this->admin_password);
     $this->bind = $bind;
 }
Example #28
0
function ldap_auth()
{
    $ldap_server = 'ldap://127.0.0.1/';
    $ldap_domain = 'dc=rugion,dc=ru';
    //$ldap_userbase = 'ou=users,ou=chelyabinsk,' . $ldap_domain;
    //$ldap_user = '******' . $_SERVER['PHP_AUTH_USER'] . ',' . $ldap_userbase;
    $ldap_user = '******';
    $ldap_pass = $_SERVER['PHP_AUTH_PW'];
    $ldapconn_s = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
    ldap_set_option($ldapconn_s, LDAP_OPT_PROTOCOL_VERSION, 3);
    if ($ldapconn_s) {
        $ldapbind_s = @ldap_bind($ldapconn_s);
        $result = ldap_search($ldapconn_s, $ldap_domain, "(&(uid=" . $_SERVER['PHP_AUTH_USER'] . ")(objectClass=sambaSamAccount)(!(sambaAcctFlags=[DU ])))");
        $info = ldap_get_entries($ldapconn_s, $result);
        $ldap_user = $info[0]["dn"];
    }
    ldap_close($ldapconn_s);
    // connect to ldap server
    $ldapconn = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    if ($ldapconn) {
        // try to bind/authenticate against ldap
        $ldapbind = @ldap_bind($ldapconn, $ldap_user, $ldap_pass) || forbidden();
        // "LDAP bind successful...";
        error_log("success: " . $_SERVER['REMOTE_ADDR'] . ', user: '******'PHP_AUTH_USER']);
    }
    ldap_close($ldapconn);
}
Example #29
0
 /**
  * Connect and bind to ldap server.
  *
  * @throws Ingo_Exception
  */
 protected function _connect()
 {
     if (!($ldapcn = @ldap_connect($this->_params['hostspec'], $this->_params['port']))) {
         throw new Ingo_Exception(_("Connection failure"));
     }
     /* Set the LDAP protocol version. */
     if (!empty($this->_params['version'])) {
         @ldap_set_option($ldapcn, LDAP_OPT_PROTOCOL_VERSION, $this->_params['version']);
     }
     /* Start TLS if we're using it. */
     if (!empty($this->_params['tls']) && !@ldap_start_tls($ldapcn)) {
         throw new Ingo_Exception(sprintf(_("STARTTLS failed: (%s) %s"), ldap_errno($ldapcn), ldap_error($ldapcn)));
     }
     /* Bind to the server. */
     if (isset($this->_params['bind_dn'])) {
         $bind_dn = $this->_substUser($this->_params['bind_dn']);
         $password = isset($this->_params['bind_password']) ? $this->_params['bind_password'] : $this->_params['password'];
         $bind_success = @ldap_bind($ldapcn, $bind_dn, $password);
     } else {
         $bind_success = @ldap_bind($ldapcn);
     }
     if ($bind_success) {
         return $ldapcn;
     }
     throw new Ingo_Exception(sprintf(_("Bind failed: (%s) %s"), ldap_errno($ldapcn), ldap_error($ldapcn)));
 }
Example #30
0
 /**
  * 
  * Verifies set of credentials.
  *
  * @param array $credentials A list of credentials to verify
  * 
  * @return mixed An array of verified user information, or boolean false
  * if verification failed.
  * 
  */
 public abstract function validateCredentials($credentials)
 {
     if (empty($credentials['handle'])) {
         return false;
     }
     if (empty($credentials['passwd'])) {
         return false;
     }
     $handle = $credentials['handle'];
     $passwd = $credentials['passwd'];
     // 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'] . ']/';
     $handle = preg_replace($regex, '', $handle);
     // bind to the server
     $rdn = sprintf($this->_config['format'], $handle);
     $bind = @ldap_bind($conn, $rdn, $passwd);
     // did the bind succeed?
     if ($bind) {
         ldap_close($conn);
         return array('handle' => $handle);
     } else {
         $this->_err = @ldap_errno($conn) . " " . @ldap_error($conn);
         ldap_close($conn);
         return false;
     }
 }