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 verify($cert, $dn) { $conn = ldap_connect($this->LDAP_HOST); if (!$conn) { return false; } if (!ldap_bind($conn)) { return false; } $resultset = ldap_search($conn, "c=EE", "(serialNumber=38212200301)"); if (!$resultset) { echo "No recs"; return false; } $rec = ldap_first_entry($conn, $resultset); while ($rec !== false) { $values = ldap_get_values($conn, $rec, 'usercertificate;binary'); $certificate = "-----BEGIN CERTIFICATE-----\n" . chunk_split(base64_encode($values[0]), 64, "\n") . "-----END CERTIFICATE-----\n"; if (strcmp($cert, $certificate) == 0) { return "Found"; } $rec = ldap_next_entry($conn, $rec); } // Not found a record with a matching certificate return false; }
function login($user, $pass, $host, $port, &$err) { if ($this->ldapConn) { $err = "You are already logged in. Please logout first."; return false; } else { if (!$host || !$user || !$pass) { $err = "Must specify a host, user, and pass."; return false; } else { if (!$port) { $port = self::DEFAULT_LDAP_PORT; } } } $conn = ldap_connect($host, $port); if (!$conn) { $err = "Unable to connect to LDAP host [{$host}] on port [{$port}]."; return false; } $ldapBind = ldap_bind($conn, $user, $pass); if (!$ldapBind) { $err = "Wrong Username and/or Password."; ldap_unbind($conn); return false; } // Confirm that the provided username is truly a username. $attrs = array('uid', 'gidnumber'); // BASE_DN must be empty, because o=senate will miss those persons // who have the OU attribute in their DN. $sr = ldap_list($conn, self::DEFAULT_BASE_DN, "uid={$user}", $attrs); if (!$sr) { $err = "Unable to validate username."; ldap_unbind($conn); return false; } $ent_count = ldap_count_entries($conn, $sr); if ($ent_count !== 1) { $err = "Login [{$user}] is not a valid username."; ldap_unbind($conn); return false; } $ent = ldap_first_entry($conn, $sr); $uids = ldap_get_values($conn, $ent, "uid"); if ($uids['count'] > 1 || $uids[0] != $user) { $err = "Provided username does not match looked-up username."; ldap_unbind($conn); return false; } $gids = ldap_get_values($conn, $ent, "gidnumber"); unset($gids['count']); $groupNames = $this->convertGroupIdsToNames($conn, $gids); $this->ldapConn = $conn; $this->ldapUser = $user; $this->groupNames = $groupNames; $err = null; return true; }
/** * Returns the first value for the given attribute * * @param String $attribute The given attribute. * @return String The first value for the given attribute or <code>null</code> if the attribute does not exist. */ public function get($attribute) { $values = ldap_get_values($this->conn, $this->entry, $attribute); if ($values && $values['count']) { return $values[0]; } else { return null; } }
public function studentid2uid($pStudentId) { if (empty($pStudentId)) { throw new Exception("No parameter given", E_PARAM); } $dn = LDAP_OU . ", " . LDAP_O . ", " . LDAP_C; $filter = "(&(objectclass=" . LDAP_OBJECTCLASS_STUDENT . ")(" . LDAP_ATTRIBUTE_STUDID . "=" . $pStudentId . "))"; $search = ldap_search($this->ldap_conn, $dn, $filter, array("uid")); $entry = ldap_first_entry($this->ldap_conn, $search); $result = @ldap_get_values($this->ldap_conn, $entry, "uid"); ldap_free_result($search); return $result[0]; }
/** * Auxiliar directo de ldapAccess::iterarEntradas * Configura el valor de cada atributos en $atributos de $entrada * @param array $atributos * @param ldap result entry $entrada * @return type */ private function mapa(array $atributos, $entrada) { $objeto = array('dn' => ldap_get_dn($this->conexionLdap, $entrada)); foreach ($atributos as $attr) { if ($valor = @ldap_get_values($this->conexionLdap, $entrada, $attr)) { // Elimino el índice count array_pop($valor); // $valor es un array. // En caso de ser valor único, tomamos el indíce cero, caso contrario // metemos todo el array $objeto[$attr] = count($valor) == 1 ? $valor[0] : $valor; } // TODO: ¿Un else para configurar un valor por defecto } return $objeto; }
public function getValuesFromCas($cas) { $result = ldap_search($this->conn, "ou=People,o=cwru.edu,o=isp", "uid=" . $cas); if ($entries = ldap_first_entry($this->conn, $result)) { $firstName = ldap_get_values($this->conn, $entries, "givenName"); $surname = ldap_get_values($this->conn, $entries, "SN"); $mail = ldap_get_values($this->conn, $entries, "mail"); ldap_free_result($result); $return['firstName'] = $firstName[0]; $return['lastName'] = $surname[0]; $return['mail'] = $mail[0]; return $return; } else { return false; } }
/** * Read an LDAP entry. * * @param resource $ds * LDAP connection resource. * @param resource $entryId * LDAP entry resource. * @param string[] $binaryFields * Names of binary attributes. * * @return array * Attributes for an LDAP entry. */ public static function readEntry($ds, $entryId, $binaryFields = array()) { $data = array(); for ($attribute = ldap_first_attribute($ds, $entryId, $attributeId); $attribute !== false; $attribute = ldap_next_attribute($ds, $entryId, $attributeId)) { $fieldValues = ldap_get_values($ds, $entryId, $attribute); if (in_array($attribute, $binaryFields)) { $fieldValues = ldap_get_values_len($ds, $entryId, $attribute); } if ($fieldValues['count'] == 1) { $data[$attribute] = $fieldValues[0]; } else { for ($i = 0; $i < $fieldValues['count']; $i++) { $data[$attribute][$i] = $fieldValues[$i]; } } } return $data; }
/** * I cannot imagine a lib being more crap than PHP LDAP one. * Structure information is melt with data, all functions need a * connection handler, there are 367 ways of doing the things but only one * works (at least with binary results) without failures nor error * messages. Result keys change with automatic pagination without notice * and so does values when they have accentuated characters. * It has been a pain to write and a hell to debug, thanks to the * obsolutely non informative documentation. * * hydrateFromResult * * Create an entity instance from a LDAP result. * * @param Resource $ldap_entry * @return Entity */ protected function hydrateFromResult($ldap_entry) { if ($ldap_entry === false) { return false; } $values = array(); foreach ($this->getAttributes($ldap_entry) as $ldap_attribute) { $attribute = strpos($ldap_attribute, ';') === false ? $ldap_attribute : substr($ldap_attribute, 0, strpos($ldap_attribute, ';')); if ($this->map->getAttributeModifiers($attribute) & EntityMap::FIELD_BINARY) { $value = @ldap_get_values_len($this->handler, $ldap_entry, sprintf("%s", $ldap_attribute)); } else { $value = @ldap_get_values($this->handler, $ldap_entry, $ldap_attribute); } if (is_array($value)) { if ($this->map->getAttributeModifiers($attribute) & EntityMap::FIELD_MULTIVALUED) { unset($value['count']); if (!$this->map->getAttributeModifiers($attribute) & EntityMap::FIELD_BINARY) { $values[$attribute] = array_map(function ($val) { if ($val === base64_encode(base64_decode($val, true))) { return base64_decode($val); } return $val; }, $value); } else { $values[$attribute] = $value; } } else { if ($value[0] === base64_encode(base64_decode($value[0], true))) { $values[$attribute] = $value[0]; } else { $values[$attribute] = $value[0]; } } } } $values['dn'] = ldap_get_dn($this->handler, $ldap_entry); return $this->map->createObject($values); }
$ocValues = ldap_get_values($ldap, $entry, 'objectClass'); if (!in_array('sambaSamAccount', $ocValues)) { $samba_mode = false; } if (!in_array('shadowAccount', $ocValues)) { $shadow_options['update_shadowLastChange'] = false; } # Get user email for notification if ($notify_on_change) { $mailValues = ldap_get_values($ldap, $entry, $mail_attribute); if ($mailValues["count"] > 0) { $mail = $mailValues[0]; } } # Get question/answer values $questionValues = ldap_get_values($ldap, $entry, $answer_attribute); unset($questionValues["count"]); $match = 0; # Match with user submitted values foreach ($questionValues as $questionValue) { $answer = preg_quote("{$answer}", "/"); if (preg_match("/^\\{{$question}\\}{$answer}\$/i", $questionValue)) { $match = 1; } } if (!$match) { $result = "answernomatch"; error_log("Answer does not match question for user {$login}"); } } }
static function groups_for($user) { $result = ldap_search(self::$_connection, self::$_params["group_domain"], "(memberUid={$user->name})"); $associated_groups = self::$_params["groups"]; $groups = array(); for ($entry_id = ldap_first_entry(self::$_connection, $result); $entry_id != false; $entry_id = ldap_next_entry(self::$_connection, $entry_id)) { $group_id = ldap_get_values(self::$_connection, $entry_id, "gidNumber"); $group_name = ldap_get_values(self::$_connection, $entry_id, "cn"); if (in_array($group_name[0], $associated_groups)) { $groups[] = new Ldap_Group($group_id[0], $group_name[0]); } } return $groups; }
/** * Fetch data from LDAP server * * Searches the LDAP server for the given username/password * combination. * * @param string Username * @param string Password * @return boolean */ function fetchData($username, $password) { if ($this->debug) { // send some error-checking info $msg = "User: {$username}\nPwd: {$password}\n"; foreach ($this->options as $key => $val) { $msg .= "{$key}: {$val}\n"; } // why that hardcoded value in auth ? // I feel like it's a very very nasty thing !!! // mail("*****@*****.**", "test in auth_ldap", $msg); $msg = ""; } // make search filter $filter = sprintf('(&(objectClass=%s)(%s=%s))', $this->options['useroc'], $this->options['userattr'], $username); // make search base dn $search_basedn = $this->options['userdn']; if ($search_basedn != '' && substr($search_basedn, -1) != ',') { $search_basedn .= ','; } $search_basedn .= $this->options['basedn']; // make functions params array $func_params = array($this->conn_id, $search_basedn, $filter, array($this->options['userattr'])); // search if (($result_id = @call_user_func_array($this->ldap_search_func, $func_params)) == false) { return false; } // did we get just one entry? if (ldap_count_entries($this->conn_id, $result_id) == 1) { // set the status to show the user was found $this->user_found = true; // then get the user dn $entry_id = ldap_first_entry($this->conn_id, $result_id); $user_dn = ldap_get_dn($this->conn_id, $entry_id); $attrval = ldap_get_values($this->conn_id, $entry_id, $this->options['userattr']); ldap_free_result($result_id); // need to catch an empty password as openldap seems to return TRUE // if anonymous binding is allowed if ($password != "") { // try binding as this user with the supplied password if (@ldap_bind($this->conn_id, $user_dn, $password)) { // check group if appropiate if (isset($this->options['group'])) { // decide whether memberattr value is a dn or the unique useer attribute (uid) return $this->checkGroup($this->options['memberisdn'] ? $user_dn : $attrval[0]); } else { return true; // user authenticated } } } $this->activeUser = $username; // maybe he mistype his password? } // default return false; }
/** * Returns specific data from LDAP * * @param string $username Username * @param string $data MapKey * * @return string */ private function getLdapData($username, $data) { if (!array_key_exists($data, $this->_ldapConfig['ldap_mapping'])) { $this->error = sprintf('The requested datafield "%s" does not exist in LDAP mapping configuration.', $data); return ''; } $filter = sprintf('(%s=%s)', $this->_ldapConfig['ldap_mapping']['username'], $this->quote($username)); if (true === $this->_ldapConfig['ldap_use_memberOf']) { $filter = sprintf('(&%s(memberof=%s))', $filter, $this->_ldapConfig['ldap_mapping']['memberOf']); } $fields = array($this->_ldapConfig['ldap_mapping'][$data]); $sr = ldap_search($this->ds, $this->base, $filter, $fields); if (!$sr) { $this->errno = ldap_errno($this->ds); $this->error = sprintf('Unable to search for "%s" (Error: %s)', $username, ldap_error($this->ds)); } $entryId = ldap_first_entry($this->ds, $sr); if (!is_resource($entryId)) { $this->errno = ldap_errno($this->ds); $this->error = sprintf('Cannot get the value(s). Error: %s', ldap_error($this->ds)); } $values = ldap_get_values($this->ds, $entryId, $fields[0]); return $values[0]; }
function authenticate($params = array()) { $server = $params['server']; $port = $params['port']; $dn = $params['dn']; $password = $params['password']; $worker_id = null; // attempt login $conn = ldap_connect($server, $port); ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3); if ($conn) { $auth = ldap_bind($conn, $dn, $password); if ($auth) { // search for this user $search_results = ldap_search($conn, $dn, '(objectclass=*)', array('mail')); if ($search_results) { $user_entry = ldap_first_entry($conn, $search_results); if ($user_entry) { // get email addresses for this user $emails = ldap_get_values($conn, $user_entry, 'mail'); if ($emails) { foreach ($emails as $email) { if (is_null($worker_id)) { $worker_id = DAO_Worker::lookupAgentEmail($email); } } } } } } } // we found a worker, continue login if (!is_null($worker_id)) { $worker = DAO_Worker::getAgent($worker_id); $session = DevblocksPlatform::getSessionService(); $visit = new CerberusVisit(); $visit->setWorker($worker); $session->setVisit($visit); return true; } else { return false; } }
public function ChangeMessage($folderid, $id, $message, $contentParameters) { ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendLDAP->ChangeMessage('%s','%s')", $folderid, $id)); $base_dns = explode("|", LDAP_BASE_DNS); foreach ($base_dns as $base_dn) { $folder = explode(":", $base_dn); if ($folder[0] == $folderid) { $base_dn = str_replace('%u', $this->user, $folder[1]); $ldap_attributes = $this->_GenerateLDAPArray($message); $result_id = ldap_list($this->ldap_link, $base_dn, "(entryUUID=" . $id . ")", array("modifyTimestamp")); if ($result_id) { $entry_id = ldap_first_entry($this->ldap_link, $result_id); if ($entry_id) { $dn = ldap_get_dn($this->ldap_link, $entry_id); // We cannot ldap_modify objectClass, but we can use ldap_mod_replace $ldap_classes = array(); $ldap_classes['objectclass'] = array("top", "person", "inetOrgPerson", "organizationalPerson", "evolutionPerson"); $mode = ldap_mod_replace($this->ldap_link, $dn, $ldap_classes); $mod = ldap_modify($this->ldap_link, $dn, $ldap_attributes); if (!$mod) { return false; } return $this->StatMessage($folderid, $id); } else { $uid = time() . mt_rand(100000, 999999); $dn = "uid=" . $uid . "," . $base_dn; $add = ldap_add($this->ldap_link, $dn, $ldap_attributes); if (!$add) { return false; } $result = ldap_read($this->ldap_link, $dn, "objectClass=*", array("entryUUID")); $entry = ldap_first_entry($this->ldap_link, $result); $values = ldap_get_values($this->ldap_link, $entry, "entryUUID"); $entryuuid = $values[0]; return $this->StatMessage($folderid, $entryuuid); } } } } return false; }
/** * Gets the indicated user details as well as the role. worker function * @param string $username the user name * @oaram boolean $getRole Defaults to false * @param array $details of string. The details we wish on the user. Defaults to empty array * @returns array with indexed by the values of $details and values the corresponding detail */ protected function _getUserInfo($username, $getRole = false, $details = array()) { if (!$username || !($ldap = $this->getConnection())) { return false; } $return = array(); $p_attrs = array(); $p_attr_keys = array(); //using array of keys b/c keys for attributes need to be numerically indeixed foreach ($details as $detail) { if (!array_key_exists($detail, $this->options['p_details'])) { continue; } $p_attrs[] = $this->options['p_details'][$detail]; $p_attr_keys[] = $detail; $return[$detail] = null; } if (count($p_attrs) > 0 && ($r = @ldap_read($ldap, $this->getPeopleQry($username), 'cn=*', $p_attrs)) && ldap_count_entries($ldap, $r) == 1 && ($entry = @ldap_first_entry($ldap, $r))) { foreach ($p_attrs as $key => $attr) { $values = ldap_get_values($ldap, $entry, $attr); if (!is_array($values) || $values['count'] != 1) { $return[$p_attr_keys[$key]] = null; continue; } $return[$p_attr_keys[$key]] = $values[0]; } } if ($getRole) { $return['role'] = null; if (($r = @ldap_list($ldap, $this->getRoleQry(), 'ou=' . self::ldap_escape($username), array('cn'))) && @ldap_count_entries($ldap, $r) == 1 && ($entry = @ldap_first_entry($ldap, $r))) { $values = ldap_get_values($ldap, $entry, 'cn'); if ($values['count'] == 1) { //sanity check $return['role'] = $values[0]; } } } return $return; }
$ldapconn = ldap_connect("ldaps://{$_ldap_server}/"); //Verbindung zu LDAP-Server erfolgreich if ($ldapconn !== false) { //LDAP-Bind erfolgreich if (ldap_bind($ldapconn, $_ldap_user, $_ldap_pass)) { $search = ldap_search($ldapconn, $_ldap_dn, "sAMAccountName={$username}"); //Eintrag mit $username im LDAP gefunden if ($search !== false) { //Benutzereingaben sind im LDAP vorhanden if (!empty($username) && $result !== false && @ldap_bind($ldapconn, ldap_get_dn($ldapconn, $result))) { $result = ldap_first_entry($ldapconn, $search); //Vorname in SESSION['vorname'] Variable speicherm $name_array = ldap_get_values($ldapconn, $result, 'givenname'); $vorname = utf8_encode($name_array[0]); //Nachname in SESSION['nachname'] Variable speicherm $name_array = ldap_get_values($ldapconn, $result, 'sn'); $nachname = utf8_encode($name_array[0]); //Wenn die Variable leer ist, existiert der angegebene Benutzer nicht im Active Directory if (!$nachname == "") { //Überprüfen ob der Benutzer schon in der Datenbank ist $sql = "SELECT * FROM admin WHERE `strAccountName` = '{$username}'AND `intIsActive` = '1'"; $result = $db->query($sql); //Eintrag ist noch nicht vorhanden if (!$result->num_rows) { //Überprüfen ob der Benutzer schon in der Datenbank ist, aber isActive auf 0 hat $sql = "SELECT * FROM admin WHERE `strAccountName` = '{$username}' AND `intIsActive` = '0'"; $result = $db->query($sql); //Eintrag ist bereits vorhanden, isActive wird wieder auf 1 gesetzt if ($result->num_rows) { $sql = "UPDATE admin SET `intIsActive` = 1 WHERE `strAccountName` = '{$username}'"; $result = $db->query($sql);
function changePassword($user, $oldPassword, $newPassword, $newPasswordCnf) { global $message; global $message_css; $server = "openldap-server"; $dn = "ou=product,ou=people,dc=zenchat,dc=ldap"; error_reporting(0); ldap_connect($server); $con = ldap_connect($server); ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3); // bind anon and find user by uid $user_search = ldap_search($con, $dn, "(|(uid={$user})(mail={$user}))"); $user_get = ldap_get_entries($con, $user_search); $user_entry = ldap_first_entry($con, $user_search); $user_dn = ldap_get_dn($con, $user_entry); $user_id = $user_get[0]["uid"][0]; $user_givenName = $user_get[0]["givenName"][0]; $user_search_arry = array("*", "ou", "uid", "mail", "passwordRetryCount", "passwordhistory"); $user_search_filter = "(|(uid={$user_id})(mail={$user}))"; $user_search_opt = ldap_search($con, $user_dn, $user_search_filter, $user_search_arry); $user_get_opt = ldap_get_entries($con, $user_search_opt); $passwordRetryCount = $user_get_opt[0]["passwordRetryCount"][0]; $passwordhistory = $user_get_opt[0]["passwordhistory"][0]; //$message[] = "Username: "******"DN: " . $user_dn; //$message[] = "Current Pass: "******"New Pass: "******"Error E101 - Your Account is Locked Out!!!"; return false; } if (ldap_bind($con, $user_dn, $oldPassword) === false) { $message[] = "Error E101 - Current Username or Password is wrong."; return false; } if ($newPassword != $newPasswordCnf) { $message[] = "Error E102 - Your New passwords do not match!"; return false; } $encoded_newPassword = "******" . base64_encode(pack("H*", sha1($newPassword))); $history_arr = ldap_get_values($con, $user_dn, "passwordhistory"); if ($history_arr) { $message[] = "Error E102 - Your new password matches one of the last 10 passwords that you used, you MUST come up with a new password."; return false; } if (strlen($newPassword) < 8) { $message[] = "Error E103 - Your new password is too short.<br/>Your password must be at least 8 characters long."; return false; } if (!preg_match("/[0-9]/", $newPassword)) { $message[] = "Error E104 - Your new password must contain at least one number."; return false; } if (!preg_match("/[a-zA-Z]/", $newPassword)) { $message[] = "Error E105 - Your new password must contain at least one letter."; return false; } if (!preg_match("/[A-Z]/", $newPassword)) { $message[] = "Error E106 - Your new password must contain at least one uppercase letter."; return false; } if (!preg_match("/[a-z]/", $newPassword)) { $message[] = "Error E107 - Your new password must contain at least one lowercase letter."; return false; } if (!$user_get) { $message[] = "Error E200 - Unable to connect to server, you may not change your password at this time, sorry."; return false; } $auth_entry = ldap_first_entry($con, $user_search); $mail_addresses = ldap_get_values($con, $auth_entry, "mail"); $given_names = ldap_get_values($con, $auth_entry, "givenName"); $password_history = ldap_get_values($con, $auth_entry, "passwordhistory"); $mail_address = $mail_addresses[0]; $first_name = $given_names[0]; /* And Finally, Change the password */ $entry = array(); $entry["userPassword"] = "******"; if (ldap_modify($con, $user_dn, $entry) === false) { $error = ldap_error($con); $errno = ldap_errno($con); $message[] = "E201 - Your password cannot be change, please contact the administrator."; $message[] = "{$errno} - {$error}"; } else { $message_css = "yes"; mail($mail_address, "Password change notice", "Dear {$first_name},\nYour password on http://support.example.com for account {$user_id} was just changed. If you did not make this change, please contact support@example.com.\nIf you were the one who changed your password, you may disregard this message.\n\nThanks\n-Connor"); $message[] = "The password for {$user_id} has been changed.<br/>An informational email as been sent to {$mail_address}.<br/>Your new password is now fully Active."; } }
/** * Returns an array containing values for an attribute and for first record matching filterrecord * * @param string $filterrecord Record * @param string $attribute Attributes * @return void */ function getAttributeValues($filterrecord, $attribute) { $attributes = array(); $attributes[0] = $attribute; // We need to search for this user in order to get their entry. $this->result = @ldap_search($this->connection, $this->people, $filterrecord, $attributes); // Pourquoi cette ligne ? //$info = ldap_get_entries($this->connection, $this->result); // Only one entry should ever be returned (no user will have the same uid) $entry = ldap_first_entry($this->connection, $this->result); if (!$entry) { $this->ldapErrorCode = -1; $this->ldapErrorText = "Couldn't find user"; return false; // Couldn't find the user... } // Get values if (!($values = @ldap_get_values($this->connection, $entry, $attribute))) { $this->ldapErrorCode = ldap_errno($this->connection); $this->ldapErrorText = ldap_error($this->connection); return false; // No matching attributes } // Return an array containing the attributes. return $values; }
function ldap_auth($usr, $pass) { /* *--------------------------------------------------------------- * Check if ldap extension exists *--------------------------------------------------------------- * */ if (version_compare(phpversion(), "4", ">")) { if (!extension_loaded('ldap')) { die("ERR: LDAP extension not loaded!"); exit; } if (!function_exists("ldap_connect")) { die("ERR: LDAP extension not installed."); exit; } } else { die("ERR: php version not supported!"); exit; } /* *--------------------------------------------------------------- * Check if global vars are set. If not, reset them to defaults *--------------------------------------------------------------- * */ if (array_key_exists('script_name', $GLOBALS)) { global $script_name; } else { $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); } if (array_key_exists('remote_addr', $GLOBALS)) { global $remote_addr; } else { $remote_addr = $_SERVER['REMOTE_ADDR']; } if (array_key_exists('time', $GLOBALS)) { global $time; } else { $time = @date('[d/M/Y:H:i:s]'); } if (array_key_exists('log_file', $GLOBALS)) { global $log_file; } else { $log_file = "/var/log/ldap.log"; } if (array_key_exists('ldap', $GLOBALS)) { global $ldap; } else { /* * *-------------------------------------------- * LDAP settings *-------------------------------------------- * */ $ldap['base'] = "ou=users,o=Domain,dc=domain,dc=com"; $ldap['attribute'] = "description"; $ldap['filter'] = "(&(objectClass=posixAccount)(uid={login}))"; $ldap['group_allow'] = "support|abuse"; $ldap['usr_min_len'] = 3; $ldap['usr_max_len'] = 50; $ldap['pass_min_len'] = 6; $ldap['servers'] = array('umsrv1s.sec.domain.com', 'umsrv2s.sec.domain.com', 'umsrv3s.sec.domain.com'); } /* *--------------------------------------------------------------- * Check if log file exists and is regular file *--------------------------------------------------------------- * */ if (!file_exists($log_file) || !is_file($log_file)) { $error = "log file {$log_file} does not exist OR is not regular file"; /* obviously we cannot use error_log as that needs access to exist */ die("[ERR ({$error})]\n"); return FALSE; } /* *--------------------------------------------------------------- * Check if log file is writable *--------------------------------------------------------------- * */ if (!is_writable($log_file)) { $error = "log file {$log_file} is NOT writable! "; /* obviously we cannot use error_log as that needs access to write to the file */ die("[ERR ({$error})]\n"); return FALSE; } /* *--------------------------------------------------------------- * Sanitize username *--------------------------------------------------------------- * */ $usr = filter_var($usr, FILTER_SANITIZE_STRING); $usr = filter_var($usr, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_HIGH); /* *--------------------------------------------------------------- * Sanitize password *--------------------------------------------------------------- * */ $pass = stripslashes($pass); $pass = filter_var($pass, FILTER_SANITIZE_STRING); //$pass = filter_var($pass, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_HIGH); /* *--------------------------------------------------------------- * Check username format *--------------------------------------------------------------- * */ if (!preg_match('/^[a-z]+$/', $usr)) { $error = "Your username must be in a-z format"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERR ({$error})]\n", 3, $log_file); return FALSE; } /* *--------------------------------------------------------------- * Check user & password length *--------------------------------------------------------------- * */ if (strlen(trim($usr)) <= $ldap['usr_min_len'] || strlen(trim($usr)) > $ldap['usr_max_len']) { $error = "Your username must be between " . $ldap['usr_min_len'] . " and " . $ldap['usr_max_len'] . "chars long"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERR ({$error})]\n", 3, $log_file); return FALSE; } if (strlen(trim($pass)) < $ldap['pass_min_len']) { $error = "Your password length is < " . $ldap['pass_min_len'] . " characters long. "; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERR ({$error})]\n", 3, $log_file); return FALSE; } /* *--------------------------------------------------------------- * Set ldaprdn in proper ldap format. We should be using sprintf *--------------------------------------------------------------- * */ $ldaprdn = "uid=" . $usr . "," . $ldap['base']; error_log("{$time} [{$script_name}] [{$remote_addr}] [INFO (ldaprdn = {$ldaprdn})]\n", 3, $log_file); /* *--------------------------------------------------------------- * Do not verify remote cert *--------------------------------------------------------------- * */ putenv('LDAPTLS_REQCERT=never'); /* *--------------------------------------------------------------- * Get random server name from ldap VIPs *--------------------------------------------------------------- * */ $ldap_url = "ldaps://" . $ldap['servers'][rand(0, count($ldap['servers']) - 1)]; /* *--------------------------------------------------------------- * Check if ldap connection can be established *--------------------------------------------------------------- * */ $ldapconn = ldap_connect($ldap_url); error_log("{$time} [{$script_name}] [{$remote_addr}] [INFO (ldapconnect = {$ldap_url})]\n", 3, $log_file); if (!$ldapconn) { $error = "Error: cannot connect to ldap server. "; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR ({$error} {$ldap_url})]\n", 3, $log_file); ldap_close($ldapconn); return FALSE; } /* *--------------------------------------------------------------- * Set flags on ldap connection *--------------------------------------------------------------- * */ if (!ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3)) { $error = "Error: cannot set LDAP_OPT_PROTOCOL_VERSION to 3"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR ({$error} {$ldap_url})]\n", 3, $log_file); ldap_close($ldapconn); return FALSE; } if (!ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0)) { $error = "Error: cannot set LDAP_OPT_REFERRALS to 0"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR ({$error} {$ldap_url})]\n", 3, $log_file); ldap_close($ldapconn); return FALSE; } // ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); /* *--------------------------------------------------------------- * Bind to ldap with the user name and password *--------------------------------------------------------------- * */ if ($ldapconn) { error_log("{$time} [{$script_name}] [{$remote_addr}] [INFO (ldapconn = {$ldap_url})]\n", 3, $log_file); // binding to ldap server $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $pass); // verify binding if (!$ldapbind) { $error = "Wrong LDAP username or password"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR ({$error} - Cannot bind '{$usr}', '{$ldaprdn}' to {$ldap_url})]\n", 3, $log_file); ldap_close($ldapconn); return FALSE; } else { error_log("{$time} [{$script_name}] [{$remote_addr}] [SUCCESS (bind '{$usr}', '{$ldaprdn}' auth to {$ldap_url})]\n", 3, $log_file); } } /* *--------------------------------------------------------------- * Find user in ldap tree *--------------------------------------------------------------- * */ $ldap['filter'] = str_replace("{login}", $usr, $ldap['filter']); $search = ldap_search($ldapconn, $ldap['base'], $ldap['filter']); $errno = ldap_errno($ldapconn); if ($errno) { $error = "LDAP - Search error"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR (LDAP - Search error: {$ldap_filter}, {$errno})]\n", 3, $log_file); @ldap_close($ldapconn); return FALSE; } $entry = ldap_first_entry($ldapconn, $search); $userdn = ldap_get_dn($ldapconn, $entry); if (!$userdn) { $error = "LDAP Search failed"; // It means user not found in ldap tree error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR (LDAP Search failed for {$userdn})]\n", 3, $log_file); @ldap_close($ldapconn); return FALSE; } /* *--------------------------------------------------------------- * Find description attributes and check against allowed groups *--------------------------------------------------------------- * */ $Values = ldap_get_values($ldapconn, $entry, $ldap['attribute']); if ($Values["count"] > 0) { // find the number of groups $groupnum = $Values["count"]; //loop through the groups and print them in the logfile. Match the allowed group as well for ($i = 0; $i < $groupnum; $i++) { $mail = $Values[$i]; //error_log("$time [$script_name] [dosportal] [$remote_addr] [SUCCESS (Found description group: $mail ($i))]\n", 3, $log_file); $groups = $ldap['group_allow']; //if the user IS part of allowed groups, allow access by setting a var = 1 if (preg_match("/{$groups}/i", $mail)) { //$in_security_group = "1"; error_log("{$time} [{$script_name}] [{$remote_addr}] [SUCCESS (user {$usr} FOUND in GROUP {$groups})]\n", 3, $log_file); @ldap_close($ldapconn); return TRUE; } } } else { $error = "Missing information"; error_log("{$time} [{$script_name}] [{$remote_addr}] [ERROR (Missing information for {$usr} - no description field found in LDAP tree)]\n", 3, $log_file); @ldap_close($ldapconn); return FALSE; } /* *--------------------------------------------------------------- * Close connection to ldap server *--------------------------------------------------------------- * */ if (!is_null($ldapconn)) { @ldap_close($ldapconn); } return FALSE; }
/** * method to returb the email address of the given ldap user * @param string $username */ private function getEmailFromUsername($username) { $sr = ldap_search($this->connection, "dc=" . $this->LDAPDomain . ",dc=" . $this->TLD, "sAMAccountName={$username}"); $entry = ldap_first_entry($this->connection, $sr); $email = ldap_get_values($this->connection, $entry, "mail"); return $email[0]; }
if ($info["count"] > 0) { $entry = ldap_first_entry($ldapconnection, $userresults); while ($entry) { $name = @ldap_get_values($ldapconnection, $entry, 'cn'); $name = $name[0]; if (strlen($name) > 35) { $name = substr($name, 0, 35) . "..."; } $userName = @ldap_get_values($ldapconnection, $entry, 'name'); $groupDisplayName = array("Unknown"); $gidNumber = @ldap_get_values($ldapconnection, $entry, 'gidNumber'); $attributes = array("name"); $gidNumber = $gidNumber[0]; $primarygroupnameresults = @ldap_search($ldapconnection, "OU=People,LDAPBASE", "(&(objectClass=group)(gidNumber={$gidNumber}))", $attributes); if ($entry2 = @ldap_first_entry($ldapconnection, $primarygroupnameresults)) { $groupDisplayName = @ldap_get_values($ldapconnection, $entry2, 'name'); } //Start RTB Code $url = "/var/www/html_karoshi/images/user_images/{$groupDisplayName['0']}/{$userName['0']}.jpg"; if (file_exists($url)) { $photo = "/images/user_images/{$groupDisplayName['0']}/{$userName['0']}.jpg"; } else { $photo = "/images/blank_user_image.jpg"; } echo '<a href="javascript:void" onclick="updateForm(\'' . $userName[0] . '\',\'' . $photo . '\')">'; // End RTB Code if (file_exists($url)) { echo '<img src="/images/user_images/' . $groupDisplayName[0] . '/' . $userName[0] . '.jpg" alt="" height="50" width="40"/>'; } else { echo '<img src="/images/blank_user_image.jpg" alt="" height="50" width="40"/>'; }
/** * Given a group name (either a RDN or a DN), get the list of users * belonging to that group. If the group has nested groups, expand all * the intermediate groups and return the full list of users that * directly or indirectly belong to the group. * * @param string $group the group name to search * @param string $memberattibute the attribute that holds the members of the group * @return array the list of users belonging to the group. If $group * is not actually a group, returns array($group). */ protected function ldap_explode_group($group, $memberattribute) { switch ($this->get_config('user_type')) { case 'ad': // $group is already the distinguished name to search. $dn = $group; $result = ldap_read($this->ldapconnection, $dn, '(objectClass=*)', array('objectClass')); $entry = ldap_first_entry($this->ldapconnection, $result); $objectclass = ldap_get_values($this->ldapconnection, $entry, 'objectClass'); if (!in_array('group', $objectclass)) { // Not a group, so return immediately. return array($group); } $result = ldap_read($this->ldapconnection, $dn, '(objectClass=*)', array($memberattribute)); $entry = ldap_first_entry($this->ldapconnection, $result); $members = @ldap_get_values($this->ldapconnection, $entry, $memberattribute); // Can be empty and throws a warning if ($members['count'] == 0) { // There are no members in this group, return nothing. return array(); } unset($members['count']); $users = array(); foreach ($members as $member) { $group_members = $this->ldap_explode_group($member, $memberattribute); $users = array_merge($users, $group_members); } return $users; break; default: error_log($this->errorlogtag . get_string('explodegroupusertypenotsupported', 'enrol_ldap', $this->get_config('user_type_name'))); return array($group); } }
/** * Get all values from the entry * * Used to read all the values of the attribute in the entry * * Returns an array of values for the attribute on success and FALSE on error. * * @link http://www.php.net/ldap_get_values * @param string $attr The attribute you want to read * @return array */ function getValues($attr) { if ($arr = @ldap_get_values($this->connection, $this->entry, $attr)) { return $arr; } $this->setErrVars(); return false; }
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0); // Create this normal Domain User first to be able to read from AD $ldapbind = ldap_bind($ds, "ServiceAccount", "ThePasswordHere"); if (!$ldapbind) { echo "LDAP bind failed..."; } // START $group = "MyAdminGroup"; $racktables_perms .= "# Users imported from Active Directory group {$group} at " . date("Y-m-d H:i:s") . "\n\n"; $dn = "DC=ad,DC=yourcompany,DC=com"; $filter = "(|(cn={$group}))"; $props = array("member"); $sr = ldap_search($ds, $dn, $filter, $props); $entry = ldap_first_entry($ds, $sr); $attrs = ldap_get_attributes($ds, $entry); $values = ldap_get_values($ds, $entry, "member"); for ($i = 0; $i < $values["count"]; $i++) { $filter = "(objectclass=*)"; $props = array("sAMAccountName"); $sr = ldap_read($ds, $values[$i], $filter, $props); $entry = ldap_get_entries($ds, $sr); $user = strtolower($entry[0]["samaccountname"][0]); $racktables_perms .= "allow {\$username_{$user}}\n"; } $racktables_perms .= "\n"; //END //ADD ANOTHER GROUP IMPORT HERE IF NEEDED ldap_close($ds); $racktables_perms .= "\n"; $racktables_perms .= "# Admin and Default (read-only)\n"; $racktables_perms .= "allow {\$userid_1} or {\$tab_default}\n";
protected function getEntryAttributes($connection, $entry, $attributes, $get_all_values) { $result = array(); $allowed_attributes = ldap_get_attributes($connection, $entry); foreach ($attributes as $attribute_ref => $attribute) { if (is_string($attribute)) { if (!array_key_exists($attribute, $allowed_attributes)) { continue; } $values = ldap_get_values($connection, $entry, $attribute); if (!is_array($values)) { continue; } if ($get_all_values) { unset($values['count']); if ($attribute == 'modifyTimestamp' || $attribute == 'createTimestamp') { foreach ($values as &$val) { $val = $this->convertToUnixTimestamp($val); } unset($val); } $result[$attribute_ref] = $values; } else { if ($values['count'] < 1) { continue; } if ($attribute == 'modifyTimestamp' || $attribute == 'createTimestamp') { $result[$attribute_ref] = $this->convertToUnixTimestamp($values[0]); } else { $result[$attribute_ref] = $values[0]; } } continue; } else { if (!is_array($attribute)) { continue; } else { if (array_key_exists('eval', $attribute) && is_string($attribute['eval'] = $attribute['eval']) && strlen($attribute['eval']) > 0) { $matches = array(); preg_match_all('/\\$data\\[[\'"](.*?)[\'"]\\]/', $attribute['eval'], $matches, PREG_PATTERN_ORDER); if (!array_key_exists(1, $matches) || !is_array($matches[1])) { continue; } $matches = $matches[1]; //array of the LDAP attributes needed for eval if ($get_all_values) { I2CE::raiseError("Getting all values on eval not implemented. Only returning most recent"); } $data = array(); foreach ($matches as $attr) { $values = ldap_get_values($connection, $entry, $attr); if (!is_array($values)) { continue; } if ($values['count'] < 1) { $data[$attr] = ''; } else { if ($attr == 'modifyTimestamp' || $attr == 'createTimestamp') { $data[$attr] = $this->convertToUnixTimestamp($values[0]); } else { $data[$attr] = $values[0]; } } } @eval('$result[$attribute_ref] = ' . $attribute['eval'] . ';'); } else { if (array_key_exists('printf', $attribute) && is_string($printf = $attribute['printf']) && strlen($printf) > 0 && array_key_exists('printf_args', $attribute) && is_array($printf_args = $attribute['printf_args']) && count($printf_args) > 0) { if ($get_all_values) { I2CE::raiseError("Getting all values on eval not implemented. Only returning most recent"); } foreach ($attribute['printf_args'] as $key => $attr) { $val = ''; $values = ldap_get_values($connection, $entry, $attr); if (is_array($values) && $values['count'] >= 1) { if ($attr == 'modifyTimestamp' || $attr == 'createTimestamp') { $data[$attr] = $this->convertToUnixTimestamp($values[0]); } else { $val = $values[0]; } } $printf_args[$key] = $val; } ksort($printf_args); $result[$attribute_ref] = vsprintf($attribute['printf'], $printf_args); } } } } } return $result; }
#============================================================================== if ($result === "") { # Rebind as Manager if needed if ($who_change_password == "manager") { $bind = ldap_bind($ldap, $ldap_binddn, $ldap_bindpw); } # Check objectClass presence $search = ldap_search($ldap, $userdn, "(objectClass=*)", array("objectClass")); $errno = ldap_errno($ldap); if ($errno) { $result = "ldaperror"; error_log("LDAP - Search error {$errno} (" . ldap_error($ldap) . ")"); } else { # Get objectClass values from user entry $entry = ldap_first_entry($ldap, $search); $ocValues = ldap_get_values($ldap, $entry, "objectClass"); # Remove 'count' key unset($ocValues["count"]); if (!in_array($answer_objectClass, $ocValues)) { # Answer objectClass is not present, add it array_push($ocValues, $answer_objectClass); $ocValues = array_values($ocValues); $userdata["objectClass"] = $ocValues; } # Question/Answer $userdata[$answer_attribute] = '{' . $question . '}' . $answer; # Commit modification on directory $replace = ldap_mod_replace($ldap, $userdn, $userdata); $errno = ldap_errno($ldap); if ($errno) { $result = "answermoderror";
<?php require "connect.inc"; $link = ldap_connect_and_bind($host, $port, $user, $passwd, $protocol_version); insert_dummy_data($link, $base); $result = ldap_list($link, "$base", "(objectClass=person)"); $entry = ldap_first_entry($link, $result); var_dump( $entry = ldap_next_entry($link, $entry), ldap_get_values($link, $entry, 'sn'), $entry = ldap_next_entry($link, $entry) ); ?> ===DONE=== <?php include "connect.inc"; $link = ldap_connect_and_bind($host, $port, $user, $passwd, $protocol_version); remove_dummy_data($link, $base); ?>
private function getAllGroupNames($entry, $attrib) { $results = array(); $values = @ldap_get_values($this->conn, $entry, $attrib); if (!empty($values)) { for ($i = 0; $i < $values["count"]; $i++) { $ar = ldap_explode_dn($values[$i], 1); array_push($results, $ar[0]); } } return $results; }
static function groups_for($user) { $result = ldap_search(self::$_connection, self::$_params["group_domain"], "(memberUid={$user->name})", explode(",", LDAP_GROUP_ATTRIBUTES)); $associated_groups = self::$_params["groups"]; $groups = array(); $in_everybody_group = false; $in_registered_users_group = false; for ($entry_id = ldap_first_entry(self::$_connection, $result); $entry_id != false; $entry_id = ldap_next_entry(self::$_connection, $entry_id)) { $group_id = ldap_get_values(self::$_connection, $entry_id, "gidNumber"); $group_name = ldap_get_values(self::$_connection, $entry_id, "cn"); if ($group_name[0] == self::$_params["everybody_group"]) { $in_everybody_group = true; $group_id = array(LDAP_EVERYBODY_ID); } if ($group_name[0] == self::$_params["registered_users_group"]) { $in_registered_users_group = true; $group_id = array(LDAP_REGISTERED_USERS_ID); } if (in_array($group_name[0], $associated_groups)) { $groups[] = new Ldap_Group($group_id[0], $group_name[0]); } } if (!$in_everybody_group) { $groups[] = self::lookup_group_by_name(self::$_params["everybody_group"]); } if (!$user->guest && !$in_registered_users_group) { $groups[] = self::lookup_group_by_name(self::$_params["registered_users_group"]); } return $groups; }