public static function lookup($query, $type) { $person_array = array(); $x500 = ldap_connect('ldap.utexas.edu'); $bind = ldap_bind($x500); $dn = "ou=people,dc=directory,dc=utexas,dc=edu"; $filter = "{$type}={$query}"; $ldap_result = @ldap_search($x500, $dn, $filter); $attributes = array('eid' => 'uid', 'email' => 'mail', 'name' => 'cn', 'firstname' => 'givenname', 'lastname' => 'sn', 'office' => 'utexasedupersonofficelocation', 'phone' => 'telephonenumber', 'title' => 'title', 'unit' => 'ou'); if ($ldap_result) { $entry_array = ldap_get_entries($x500, $ldap_result); for ($i = 0; $i < count($entry_array) - 1; $i++) { $person = array(); if ($entry_array[$i]) { $eid = $entry_array[$i]['uid'][0]; foreach ($attributes as $label => $att) { if (isset($entry_array[$i][$att])) { $person[$label] = $entry_array[$i][$att][0]; } else { $person[$label] = ''; } } } $person_array[] = $person; } ldap_close($x500); } return $person_array; }
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>"; } }
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; }
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; }
public function checkLogin($username, $password) { if (!$username || !$password) { return false; } $username = $this->escapeUsername($username); if (!$username) { return false; } $this->bind(); $dn = 'cn=' . $username . ',' . $this->config['dn']; $authenticated = ldap_bind($this->connection, $dn, $password); if (!$authenticated) { return false; // User details where invalid } $result = ldap_search($this->connection, $this->config['dn'], 'cn= ' . $username); if (!$result) { return false; // Couldn't find user } $info = ldap_get_entries($this->connection, $result); $user_id = intval($info[0]['uid'][0]); if (!$user_id) { return false; // No user_id defined, or invalid } return $user_id; // Login successful }
/** * 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); } } }
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; } }
public function __construct($userKey) { $config = new Configuration(); //try to connect to ldap if the settings are entered if ($config->ldap->host) { //If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and set this parameter as ldaps://hostname/. //note that connect happens regardless if host is valid $ds = ldap_connect($config->ldap->host); //may need ldap_bind( $ds, $username, $password ) $bd = ldap_bind($ds) or die("<br /><h3>" . _("Could not connect to ") . $config->ldap->host . "</h3>"); if ($bd) { $filter = $config->ldap->search_key . "=" . $userKey; $sr = ldap_search($ds, $config->ldap->base_dn, $filter); if ($entries = ldap_get_entries($ds, $sr)) { $entry = $entries[0]; $fieldNames = array('fname', 'lname', 'email', 'phone', 'department', 'title', 'address'); foreach ($fieldNames as $fieldName) { $configName = $fieldName . '_field'; $this->{$fieldName} = $entry[$config->ldap->{$configName}][0]; } $this->fullname = addslashes($this->fname . ' ' . $this->lname); } ldap_close($ds); } } }
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; }
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; }
function search_uidspip ($filter,$ldap_server, $ldap_port, $dn) { global $ldap_grp_attr; // LDAP attributs $ldap_grp_attr = array ( "cn", "memberuid" ); $ds = @ldap_connect ( $ldap_server, $ldap_port ); if ( $ds ) { $r = @ldap_bind ( $ds ); // Bind anonyme if ($r) { $result=@ldap_list ($ds, $dn["groups"], $filter, $ldap_grp_attr); if ($result) { $info = ldap_get_entries( $ds, $result ); if ($info["count"]) { // Stockage des logins des membres des classes // dans le tableau $ret $init=0; for ($loop=0; $loop < $info["count"]; $loop++) { $group=split ("[\_\]",$info[$loop]["cn"][0],2); for ( $i = 0; $i < $info[$loop]["memberuid"]["count"]; $i++ ) { $ret[$init]["uid"] = $info[$loop]["memberuid"][$i]; $ret[$init]["cat"] = $group[0]; $init++; } } } ldap_free_result ( $result ); } } @ldap_close ( $ds ); } return $ret; }
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; }
/** * Authentication with username/password * * @access public * @param resource $ldap * @param string $username * @param string $password * @return boolean */ public function authenticate($ldap, $username, $password) { if (!ldap_bind($ldap, $username, $password)) { throw new ClientException('Unable to perform anonymous binding'); } return true; }
function authenticate($username, $password) { global $error; sleep(1); $server = "ldap.rit.edu"; //RIT LDAP Server $basedn = "ou=people,dc=rit,dc=edu"; //Base DN $script = $_SERVER['SCRIPT_NAME']; $filter = "(uid={$username})"; //$filter="(&(|(!(displayname=Administrator*))(!(displayname=Admin*)))(uid=$username))"; //define an appropriate ldap search filter to find your users, and filter out accounts such as administrator(administrator should be renamed anyway!). $dn = "uid={$username}, "; if (!($connect = ldap_connect($server))) { return 0; } ini_set("display_errors", "0"); if (!($bind = ldap_bind($connect, "{$dn}" . $basedn, $password)) || empty($password)) { $error = "You either have a wrong username or wrong password"; return 0; } ini_set("display_errors", "1"); $sr = ldap_search($connect, $basedn, "{$filter}"); $info = ldap_get_entries($connect, $sr); $_SESSION['accountUserName'] = $username; $_SESSION['accountFirstName'] = $info[0]['givenname'][0]; $_SESSION['accountLastName'] = $info[0]['sn'][0]; $_SESSION['accountPhone'] = $info[0]['telephonenumber'][0]; $_SESSION['accountEmail'] = $info[0]['mail'][0]; $_SESSION['accountType'] = $info[0]['riteduaccounttype'][0]; return 1; }
function ldap_call($connection, $bind_user, $bind_pass, $filter) { $ds = ldap_connect($connection); //echo $connection . $bind_user . $bind_pass . $filter ; //personal e-mails if ($ds) { $r = ldap_bind($ds, $bind_user, $bind_pass); //$filter="(|(mail= null)(objectCategory=group))"; $sr = ldap_search($ds, "ou=LMC, dc=lamontanita, dc=local", $filter); ldap_sort($ds, $sr, "cn"); $info = ldap_get_entries($ds, $sr); //echo $info["count"] . " results returned:<p>"; echo "<table id='ldaptable' border=1><tr><th>Name</th><th>E-mail</th></tr>"; for ($i = 0; $i < $info["count"]; $i++) { if ($info[$i]["mail"][0] != null) { echo "<td>" . $info[$i]["cn"][0] . "</td>"; echo "<td>" . $info[$i]["mail"][0] . "</td></tr>"; } } echo "</table>"; return $info; ldap_close($ds); } else { echo "<h4>LDAP_CALL unable to connect to LDAP server</h4>"; } }
function is_prof($login) { global $ldap_server, $ldap_port, $dn; global $error; $error = ""; $filter = "(&(cn=profs*)(memberUid={$login}))"; $ldap_groups_attr = array("cn", "memberUid"); /*-----------------------------------------------------*/ $ds = @ldap_connect($ldap_server, $ldap_port); if ($ds) { $r = @ldap_bind($ds); if (!$r) { $error = "Echec du bind anonyme"; } else { // Recherche du groupe d'appartenance de l'utilisateur connecte $result = @ldap_list($ds, $dn["groups"], $filter, $ldap_groups_attr); if ($result) { $info = @ldap_get_entries($ds, $result); if ($info["count"]) { $is_prof = true; } else { $is_prof = false; } } } } @ldap_unbind($ds); @ldap_close($ds); return $is_prof; }
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); }
function DoTest($testname, $param, $hostname, $timeout, $params) { global $NATS; $url = $params[0]; $bind = $params[1]; $pasw = $params[2]; $base = $params[3]; $filter = $params[4]; $ds = ldap_connect($url); if (!$ds) { return -2; } $ldap = $bind && $pasw ? ldap_bind($ds, $bind, $pasw) : ldap_bind($ds); if (!$ldap) { return -1; } if ($base && $filter) { $search = ldap_search($ds, $base, $filter); $val = ldap_count_entries($ds, $search); } else { $val = 1; } ldap_close($ds); return $val; }
public function login($username, $password) { // first check to see if we are already signed in if ($this->getSingleSignOnUsername() != "" && strcmp($this->getSingleSignOnUsername(), $username) == 0) { // we're logged in already return true; } else { // log in via LDAP $ldaprdn = "uid=" . $username . ',' . SSO_BASE_DN; $ldappass = $password; // connect to ldap server $ldapconn = $this->connect(SSO_LDAP_HOST, SSO_LDAP_PORT); if ($ldapconn) { // binding to ldap server $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass); // verify binding if ($ldapbind) { $this->createSingleSignOnCookie($username, $password); return true; } else { return false; } } else { $this->connectionStatus = 0; return false; } } }
/** * 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; } }
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(); }
function authenticate() { error_reporting(0); //stops it from sending errors about not being able to bind when invalid username/password entered. if (!isset($_SERVER['PHP_AUTH_USER'])) { //this sets username and password to an invalid setting so that it doesn't bind anonomously $user = "******"; $pass = "******"; } else { $user = $_SERVER['PHP_AUTH_USER']; $pass = $_SERVER['PHP_AUTH_PW']; } $ldap = ldap_connect('ad.hud.ac.uk'); if (!$ldap) { print "<br>connection error"; exit; } $ad_validate = ldap_bind($ldap, $user . '@ad.hud.ac.uk', $pass); //check if AD credentials are correct $this->db_connect(); $registered_user = mysql_query("SELECT userID, dept, accesslevel FROM users WHERE userID = '" . $user . "'"); $app_validate = mysql_num_rows($registered_user); //check if user is registered with the system if (!$ad_validate || !$app_validate) { header('WWW-Authenticate: Basic realm="ILP"'); header('HTTP/1.0 401 Unauthorized'); die("Not authorized, contact <a href='mailto:i.mcnaught@hud.ac.uk'>Ian McNaught</a> for access"); exit; } $user = mysql_fetch_assoc($registered_user); session_start(); $_SESSION['user'] = $user; }
/** * 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))); } }
/** * Function to authenticate users via LDAP * * @param string $authUser - Username to authenticate * @param string $authPW - Cleartext password * @return NULL on failure, user's info (in an array) on bind */ function ldapAuthenticate($authUser, $authPW) { global $AUTHCFG; if (empty($authUser) || empty($authPW)) { return false; } $conn = ldapConnectServer(); if ($conn == NULL) { return false; } $retval = false; $filter = $AUTHCFG['ldap_account'] . '=' . $authUser; $ident = @ldap_search($conn, $AUTHCFG['ldap_basedn'], $filter); if ($ident) { $result = @ldap_get_entries($conn, $ident); if ($result[0]) { // dn is the LDAP path where the user was fond. This attribute is always returned. if (@ldap_bind($conn, $result[0]["dn"], $authPW)) { $retval = true; } } ldap_free_result($ident); } ldap_unbind($conn); return $retval; }
private function bindLDAP($strDN, $strPWD, $bSearch) { $ldap = ldap_connect("ldaps://{$this->strHost}:636") or $ldap = false; if ($ldap) { //Connected successfully to ldap server $this->logwriter->debugwrite('Successfully Connected to LDAP Server'); $res = ldap_bind($ldap, $strDN, $strPWD) or $res = false; if ($res) { //Succcessfully bound with search DN login $this->logwriter->debugwrite("Successfully Bound with Search DN: {$strDN} Passwd: {$strPWD}"); return $ldap; } else { if ($bSearch) { $this->failure(3, array($strDN, $strPWD, ldap_error($ldap))); } else { $this->failure(7, array($strDN, $strPWD, ldap_error($ldap))); } } } else { if ($bSearch) { $this->failure(2, array($this->strHost)); } else { $this->failure(6, array($this->strHost)); } } }
public function __construct($user) { $this->_id = $user; /* Connect to the IU's ADS server */ $ds = ldap_connect(LDAP_HOST, LDAP_PORT) or die("Could not connect to ads.iu.edu:636 server"); ldap_bind($ds, LDAP_USER . "," . LDAP_BASEDN, LDAP_PWD) or die("LDAP bind to ADS failed."); /* Search for a particular user information (Only required info) */ $reqatr = array("mail", "displayName", "givenName", "title"); $result = ldap_search($ds, LDAP_BASEDN, "(sAMAccountName={$this->_id})", $reqatr) or die("Search: No ADS entry has been found for the current user."); /* Each node in a directory tree has an entry. */ $entry = ldap_first_entry($ds, $result); while ($entry) { /* Each entry is a set of attribute value pairs */ /* Extracting only required values */ /* Also assuming there is only single value */ $this->_email = ldap_get_values($ds, $entry, "mail"); $this->_email = $this->_email[0]; /* Php 5.3 */ $this->_name = ldap_get_values($ds, $entry, "displayName"); if (is_null($this->_name)) { $this->_name = ldap_get_values($ds, $entry, "givenName"); } $this->_name = $this->_name[0]; /* Php 5.3 */ $this->_instructor = ldap_get_values($ds, $entry, "title"); $this->_instructor = $this->_instructor[0]; /* Not expecting multiple entries */ /* $entry = ldap_next_entry($ds, $result); */ $entry = null; } }
function authenticate($username, $password) { global $config, $ds; if ($username && $ds) { // bind with sAMAccountName instead of full LDAP DN if (ldap_bind($ds, "{$username}@{$config['auth_ad_domain']}", $password)) { // group membership in one of the configured groups is required if (isset($config['auth_ad_require_groupmembership']) && $config['auth_ad_require_groupmembership'] > 0) { $search = ldap_search($ds, $config['auth_ad_base_dn'], "(samaccountname={$username})", array('memberOf')); $entries = ldap_get_entries($ds, $search); $user_authenticated = 0; foreach ($entries[0]['memberof'] as $entry) { $group_cn = get_cn($entry); if (isset($config['auth_ad_groups'][$group_cn]['level'])) { // user is in one of the defined groups $user_authenticated = 1; } } return $user_authenticated; } else { // group membership is not required and user is valid return 1; } } else { return 0; } } else { echo ldap_error($ds); } return 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; }
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); }
/** * 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); }