LDAP search get user givenname by userid - php

I have successfully run ldap_connect and ldap_bind commands in my php script. Now I need to get guvenName by user id. How can i do this.
$username = $_POST['username'];
$password = $_POST['password'];
define('LDAP_SERVER', 'localhost');
define('LDAP_PORT', 389);
define('LDAP_TOP', 'ou=people,dc=domain,dc=com');
$ds = ldap_connect(LDAP_SERVER, LDAP_PORT);
if (!$ds) {
echo "FALSE";
}
if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
#ldap_close($ds);
echo "FALSE";
}
$dn = 'uid=' . $username . "," . LDAP_TOP;
if (!ldap_bind($ds, $dn, $password)) {
echo "FALSE";
}

In general it's quite simple
public function getusercn($accountname)
{
$filter_person = "(&(sAMAccountName={$accountname}))";
$sr_person = ldap_search($this->ds_ad,$this->base_user_dn,$filter_person);
$sr = ldap_get_entries($this->ds_ad, $sr_person);
$attr = $sr[0]["givenName"][0];
return $attr;
}
$this->ds_ad - it's $ds in your code
$this->base_user_dn - is base OU from which you want to search (like LDAP_TOP in your case)
sAMAccountName - is "user id" attribute in your case uid
givenName - is attribute what you are looking for
All of attributes are already in $sr variable, so you can use var_dump to inspect all content.

Related

Login System in PHP for multi user

I am making a login system in php xampp. After correct authentication of the user they get redirected depending on what role they play. For Admin it goes to Admin Page and for Sales Person it goes to the main menu. In the code below you can see how the login is setup. Now my problem is: For example more than one user login as Sales they will be redirected to the main menu page. Now lets say user x logs in first then user y logs in. Now both are at the main menu page. Now when I refresh the page of the main menu I see user y's name even though I am as user x and on the same main menu page.
function Encrypt($Word)
{ //Encryption method
$ciphering = "AES-128-CTR"; //method of encryption
$options = 0;
// Non-NULL Initialization Vector for Encryption
$Encryption_iv = '1234567891011121';
// Store the Encryption key
$Encryption_key = "GeeksforGeeks";
// Use openssl_Encrypt() function to Encrypt the data
return openssl_encrypt($Word, $ciphering, $Encryption_key, $options, $Encryption_iv);
}
//Getting user information. SQL injection protection and XSS Attack.
$username = (htmlspecialchars(mysqli_real_escape_string($con, $_POST['user'])));
$password = htmlspecialchars(mysqli_real_escape_string($con, $_POST['pass']));
/* $UserOption = (htmlspecialchars(mysqli_real_escape_string($con, $_POST['Level'])));
$PinCode = htmlspecialchars(mysqli_real_escape_string($con, $_POST['Pin'])); */
$Option = htmlspecialchars(mysqli_real_escape_string($con, $_POST['option']));
$Hash = Encrypt($username);
$SalesHash = Encrypt($username);
$GetActivestmt = $con->prepare("SELECT Active FROM logins WHERE Username=?");
$GetActivestmt->bind_param("s", $Hash);
$GetActivestmt->execute();
$ActiveResult = $GetActivestmt->get_result();
//Fetching
if ($ActiveResult->num_rows === 0) exit("No Records");
while ($Active = $ActiveResult->fetch_assoc()) {
$ActiveRow = $Active['Active'];
}
$GetActivestmt->close();
global $ActiveRow;
$con->next_result();
/* if($UserOption == $row['User_Type'] && $Hash==$row['Username'] && password_verify($password, $row['HashPassword'])
&& $PinCode ==$row['PinCode']){
echo $row['User_Type'];
}else if($UserOption == $row['User_Type'] && $Hash==$row['Username']
&& password_verify($password, $row['HashPassword']) && $PinCode == $row['PinCode']){
echo $row['User_Type'];
}else{
echo '<script>alert("Info Mis-Match");</script>';
exit();
} */
if ($ActiveRow === 0) {
$GetLoginstmt = $con->prepare("SELECT * FROM logins WHERE Username=? LIMIT 1;");
$GetLoginstmt->bind_param("s", $Hash/* , $PinCode */);
$GetLoginstmt->execute();
$LoginResult = $GetLoginstmt->get_result();
//Fetching
if ($LoginResult->num_rows === 0) exit('<script>alert("User not found");</script>');
while ($Login = $LoginResult->fetch_assoc()) {
$Username = $Login['Username'];
$HashPassword = $Login['HashPassword'];
$UserType = $Login['User_Type'];
$Pin = $Login['PinCode'];
$ID = $Login['ID'];
}
$GetLoginstmt->close();
global $Username, $HashPassword, $UserType, $Pin;
echo "<script>alert('$Username');</script>";
$con->next_result();
if (
$Hash == $Username && password_verify($password, $HashPassword)
&& $Option == $UserType
) {
echo "<br/>";
if ($Option == "Admin") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$Hash')");
if ($UpdateItems) {
$_SESSION['HashUsername'] = $Hash;
$_SESSION['datetime'] = date('Y/m/d'); //storing date in datetime session
$url = "../PinCodes/VerifyPinForm.php"; //url to be redirected
echo '<script language="javascript">window.location.href ="' . $url . '"</script>'; //redirects the user to the main page
} else {
echo "Error in Query";
}
} else if ($Option == "Sales") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$SalesHash')");
if ($UpdateItems) {
$_SESSION['SalesHash'] = $Username;
$_SESSION['User_ID'] = $ID;
// setcookie("Username", $Hash, time()+84600, "/", '', '', true);
$_SESSION['datetime'] = date('Y/m/d'); //storing date in datetime session
$url1 = "../MainMenu/main.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
} else {
echo "Error";
}
} else {
echo '<script>alert("Incorrect User Info");</script>';
}
} else {
echo '<script>alert("User Already Logged in.");</script>';
global $username, $password, $Option;
$_SESSION['HashUsername'] = $Hash;
$_SESSION['datetime'] = date("Y/m/d");
$_SESSION['SalesHash'] = $SalesHash;
if ($Option == "Sales") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$SalesHash')");
if ($UpdateItems) {
$url1 = "../MainMenu/main.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
} else if ($Option == "Admin") {
$UpdateItems = mysqli_query($con, "CALL Update_Items('$Hash')");
if ($UpdateItems) {
$url1 = "../PinCodes/VerifyPinForm.php";
echo '<script language="javascript">window.location.href ="' . $url1 . '"</script>';
}
}
}
$con->close();
?>
<?php
require '../connection1.php';
function Decrypt($Word)
{ //decrypting data using openssl decrypt method
$ciphering = "AES-128-CTR";
$options = 0;
// Non-NULL Initialization Vector for decryption
$decryption_iv = '1234567891011121';
// Store the decryption key
$decryption_key = "GeeksforGeeks";
// Use openssl_decrypt() function to decrypt the data
return openssl_decrypt($Word, $ciphering, $decryption_key, $options, $decryption_iv);
}
if ($con) {
session_regenerate_id(true);
$User = $_SESSION['SalesHash'];
$UserID = $_SESSION['User_ID'];
$GetInfo = $con->prepare("SELECT * FROM logins WHERE Username=? AND ID=?");
$GetInfo->bind_param("si", $_SESSION['SalesHash'], $_SESSION['User_ID']);
$GetInfo->execute();
$GetResult = $GetInfo->get_result();
//Fetch info
if ($GetResult->num_rows === 0) exit(header("Location: ../Login/LogoutForm.html"));
while ($row = $GetResult->fetch_assoc()) {
$Active = $row['Active'];
$Username = $row['Username'];
$LoginTime = $row['Last_Login'];
$UserType = $row['User_Type'];
$ID = $row['ID'];
}
$GetInfo->close();
global $Active, $Username, $LoginTime;
}
if ($Active == 1 && $UserType == "Sales" && $Username == $User) {
} else {
header("Location: ../Login/Logout.html");
}
?>
This code is the main menu page. Now I don't know where I am going wrong.
I have started the session from xampp php.ini file.
You wouldn't need to store each salesperson in a session. What you want to do is store one user in the session, then have that user have access to many salespersons.
For instance your user table might have id, email address and password columns.
Then, your salespersons table would have id, user_id, and name.
In you session, you'd store which user_id was logged in. Then, one your page you could query something like SELECT * FROM salespersons WHERE user_id = $session['user_id']
If you use a modern PHP framework like Laravel you can handle this easily with relationships:
https://laravel.com/docs/7.x/eloquent-relationships
User authentication also comes baked out of the box:
https://laravel.com/docs/7.x/authentication
Edit: maybe I'm misunderstanding your question. If you dont want one user to access multiple salespeople, you don't need to worry about separating the sessions. A session by it's nature is a single user accessing your service. If you research how php sessions work there's a ton of resources out there to help get you started.

LDAP add user false success

i try to add a user to freeipa with the code below. the code return success but when i go to the freeipa UI the user is not visible. if i try to reinsert it will fail telling that user already exist. what can be? thanks
$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=admin))");
$user_get = ldap_get_entries($con, $user_search);
$user_entry = ldap_first_entry($con, $user_search);
$user_next = ldap_next_entry($con, $user_entry);
$user_dn = ldap_get_dn($con, $user_next);
if (ldap_bind($con, $user_dn, "adminpass") === false) {
$message[] = "Error E101 - Current Username or Password is wrong.";
}else{
$info['givenName'] = "test";
$info['cn'] = "test";
$info['sn'] = "user";
$info['mail'] = "test#localhost";
$info['objectclass'][0] = "inetorgperson";
if(ldap_add($con, "cn=test,cn=users,cn=accounts,dc=domain,dc=net", $info) === false){
$error = ldap_error($con);
$errno = ldap_errno($con);
$message[] = "$errno - $error";
}else{
$message[] = "ok";
}
}

PHP LDAP Connection

I was sent the following LDAP parameters, but am not sure how to establish a connection in PHP. I'm not sure which PHP function to use with each set of parameters. Here are the parameters I was given:
Server: ldaps://the_server.com:636
root DN: dc=the_info,dc=more_info,dc=com
User search base: ou=CompanyUsers
User search filter: sAMAccountName={0}
Group search base: OU=Security,OU=CompanyGroups
Group search filter: cn={0}
Group membership: Group membership attribute = memberOf
Display Name LDAP attribute: displayname
Email Address LDAP atribute: mail
If someone could provide a php script for me that would be great! This is my first time using LDAP and still do not understand all these parameters.
Following is the working code for linux base ldap.
It might be helpful to you.
<?php
$username = 'uid=amitkawasthi,ou=CompanyUsers,dc=the_info,dc=more_info,dc=com';
$password= 'test';
$ds=ldap_connect("the_server.com, 636");
echo $ds;
if ($ds) {
echo "Binding ...";
$r=ldap_bind($ds, $username, $password);
if ($r)
{
$sr=ldap_search($ds,"ou=CompanyUsers,dc=the_info,dc=more_info,dc=com", "uid=amitkawasthi");
$entry = ldap_first_entry($ds, $sr);
$attrs = array();
$attribute = ldap_first_attribute($ds,$entry,$identifier);
while ($attribute) {
$attrs[] = $attribute;
$attribute=ldap_next_attribute($ds,$entry,$identifier);
}
echo count($attrs) . " attributes held for this entry:<p>";
$ldapResults = ldap_get_entries($ds, $sr);
//for ($item = 0; $item < $ldapResults['count']; $item++) {
// for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++) {
//echo $data = $ldapResults[$item][$attribute];
echo $data = $ldapResults[0][$attribute];
echo $data.": ".$ldapResults[0][$data][0]."<br>";
//}
///echo '<hr />';
echo "OK";
}
else
{
echo "Fail";
}
}
?>
============================

Warning: ldap_search(): Search: Bad search filter

I am trying to create a login page using PHP.
Goals:
1. The user is able to sign in using the same username/password he uses when logging into Windows
2. The user will be redirected to a page depending on the group he belongs to
So the 1st goal is solved. The problem now is the 2nd goal.
I get an error when I run the script:
Warning: ldap_search(): Search: Bad search filter
Script:
$ldap['user'] = "domain\user123";
$ldap['pass'] = "password123";
$ldap['host'] = 'site.domain.com';
$ldap['port'] = 389;
$ldap['dn'] = "DC=site, DC=domain, DC=com";
$ldap_user_group = "User";
$ldap_manager_group = "Admin";
$ldap['conn'] = ldap_connect( $ldap['host'], $ldap['port'] )
or die("Could not connect to {$ldap['host']}" );
$ldap['bind'] = ldap_bind($ldap['conn'], $ldap['user'], $ldap['pass']);
if( !$ldap['bind'] )
{
echo "Login Failed";
}
else if( $ldap['bind'] )
{
$filter = "(sAMAccountName=" . $ldap['user'] . ")";
$attr = array("memberof");
$result = ldap_search($ldap['conn'],$ldap['dn'], $filter, $attr)
or exit("Unable to search LDAP server");
$entries = ldap_get_entries($ldap['conn'], $result);
ldap_unbind($ldap);
foreach($entries[0]['memberof'] as $grps)
{
if (strpos($grps, $ldap_manager_group))
{
//redirect to Admin page
}
if (strpos($grps, $ldap_user_group))
{
//redirect to User page
}
}
I'm really lost as I have no idea what must be causing this error.
You get a bad search filter as you are passing in a slash into the filter. You are using $ldap['user'] = "domain\user123"; in your filter here $filter = "(sAMAccountName=" . $ldap['user'] . ")";
Depending on your AD setup, you'll probably want to use something like $filter = "(sAMAccountName=user123)";

Verifying user is part of ldap/active directory security group

Ok... I've dug through the examples and etc on here and I'm still having issues.
<?php
// SHOW ERRORS 0=NO 1=YES
ini_set('display_errors', '1');
//USER
$valid_session_username = $_POST["username"];
$valid_session_password = $_POST["password"];
//MEMBER OF THIS GROUP
$dn = "DC=FLRC,DC=local";
$group = "CN=Internet-Purchasing-Allowed,OU=Security Groups,DC=FLRC,DC=LOCAL";
$filter = "(&(objectClass=user)(memberOf=$group))";
$ad = ldap_connect("srv-flc-dc03") or die("Couldn't connect to AD!");
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ad, LDAP_OPT_REFERRALS,0);
$bd = ldap_bind( $ad, $valid_session_username."#flrc.local", $valid_session_password) or die("Can't bind to server.");
$sr = ldap_search($ad, $dn, $filter);
$found = false;
if ($sr !== false) {
$count = ldap_count_entries ($ad, $sr);
if ($count !== false && $count > 0) {
$found = true;
}
}
if ($found === true) {
print $valid_session_username.' does have access to this page';
} else {
print $valid_session_username.' does NOT have access to this page';
}
?>
I have no idea what I'm missing. When I submit my credentials it says "SRAY does have access to this page". Which is what it is suppose to say since SRAY is part of that group. It also says this for another username/pass that is NOT part of that security group.
Your filter is looking for any user that is a direct member of the Internet-Purchasing-Allowed group. You need to add (sAMAccountName=$valid_session_username) to your filter.
You must define sAMAccountname in your filter
//MEMBER OF THIS GROUP
$dn = "DC=FLRC,DC=local";
$group = "CN=Internet-Purchasing-Allowed,OU=Security Groups,DC=FLRC,DC=LOCAL";
$filter = "(&(objectClass=user)(sAMAccountname=".$valid_session_username.")(memberOf=".$group."))";
You must bind the LDAP with an account that has the necessary rights. Create an administrator account that has read permissions on all the "OU=Security Groups". Then bind with it in your code.
$bd = ldap_bind( $ad, $admin_session_username."#flrc.local", $admin_session_password) or die("Can't bind to server.");

Categories