Create user in LDAP, authentication failed - php

When creating the user I cannot start the section with the user's password. The user is created, but when testing the connection, it marks invalid credentials. Can you tell me where I am wrong? How should the password be encrypted?
$ds = '192.168.1.10';
$portldap = 389;
$ldap_username = 'CN=Administrador,CN=Users,DC=Local,DC=com';
$ldap_password = 'rootadm1';
$ldap_password_user = $ldap_password;
$ldap_connection = ldap_connect($ds, $portldap);
if($ldap_connection ){
// We have to set this option for the version of Active Directory we are using.
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.
$r = ldap_bind($ldap_connection, $ldap_username, $ldap_password);
if($r === TRUE){
$CN = htmlspecialchars($_POST["cn"]);
$ldaprecord['cn'] = $CN;
$ldaprecord['sAMAccountName'] = $_POST["sAMAccountName"]; //20caract
$ldaprecord['userPrincipalName'] = $_POST["userprincipalname"];
$ldaprecord["objectClass"][0] = "top";
$ldaprecord["objectClass"][1] = "person";
$ldaprecord["objectClass"][2] = "organizationalPerson";
$ldaprecord["objectClass"][3] = "user";
$ldaprecord['description']= $_POST["description"];
$ldaprecord["userAccountControl"][0] = "66656";
$ldap_new = 'CN='.$CN.',CN=Users,DC=Local,DC=com';
$result = ldap_add($ldap_connection, $ldap_new, $ldaprecord);
if($result) {
//Success creating user - Add password
$addPrecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',md5($ldap_password_user)));
//$addPrecord["unicodePwd"][0] = iconv( 'UTF-8', 'UTF-16LE', $ldap_password_user );
$add_record= ldap_modify($ldap_connection, $ldap_new, $addPrecord);
if($add_record){
ldap_close($ldap_connection);
return $result;
}
else {
echo "LDAP Error: ".ldap_error($ldap_connection)."\n";
exit;
}
}
else {
echo "LDAP Error: ".ldap_error($ldap_connection)."\n";
exit;
}
}
}
else {
echo "cannot connect to LDAP server at $ds.";
} ```
[enter image description here][1]
[1]: https://i.stack.imgur.com/QOzqZ.png

Related

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";
}
}

LDAP can't bind to server after turn on LDAP Server Signing Requirements

As the title, any solution for it?
I used PHP function ldap_bind($server, $username, $password) to bind the ldap server,
if the signing requirement is 'none', it's working,
but if changed to 'Require signature', ldap_bind return fail.
so how can I bind to LDAP server using PHP with 'Require signature'?
try This Code I am using that code for my Local LDAP SERVER
<?php
$ldapconfig['host'] = 'localhost';
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=test,dc=example,dc=com';
$ldapconfig['authrealm'] = 'Nisarg';
function ldap_authenticate() {
global $ldapconfig;
global $PHP_AUTH_USER;
global $PHP_AUTH_PW;
//$PHP_AUTH_USER = "john";
//$PHP_AUTH_PW = "esparkinfo";
$PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER'];
$PHP_AUTH_PW = $_SERVER['PHP_AUTH_PW'];
if ($PHP_AUTH_USER != "" && $PHP_AUTH_PW != "") {
$ds=#ldap_connect($ldapconfig['host'],$ldapconfig['port']);
$r = #ldap_search( $ds, $ldapconfig['basedn'], 'uid=' . $PHP_AUTH_USER);
if ($r) {
$result = #ldap_get_entries( $ds, $r);
if ($result[0]) {
if (#ldap_bind( $ds, $result[0]['dn'], $PHP_AUTH_PW) ) {
return $result[0];
}
}
}
}
header('WWW-Authenticate: Basic realm="'.$ldapconfig['authrealm'].'"');
header('HTTP/1.0 401 Unauthorized');
return NULL;
}
if (($result = ldap_authenticate()) == NULL) {
echo('Authorization Failed');
exit(0);
}
echo('Authorization success');
echo "<pre>";
print_r($result);
echo"<pre>";
print_r($_SERVER);
die;
?>
You need to implement your code to use LDAPS (LDAP over TLS).

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.");

Codeigniter single site log on

I am trying to have it so if I log on from 1 part of my site, it will log on to the other parts also.
Some Notes:
All logins connect to the same database... lets call it db1
Site 1's table is phpfox
Site 2's table is vbulletin
Right now it successfully logs into phpfox but I can't figure out how to login to the forums also.... I've added a few lines of code below to try to do this but I can't figure it out:
The problem is I have to keep logging in on each part of my website (using the same username and password)
Here is my current code:
function login($username, $password, $passClean = null)
{
$this->faildLogins = new DB_FaildLogins();
$ip = $this->input->ip_address();
$faildLogins = $this->faildLogins->getFaildLoginsByIp($ip);
if($faildLogins){
if($faildLogins->bannedTime > 0){
$timeElapsed = ($faildLogins->lastTryDate + $faildLogins->bannedTime)-time();
if($timeElapsed > 0){
return sprintf('Your ip (%s) was banned for %s please try again after expire ban time!', $this->input->ip_address(), seconds2HumanTimeFormat($timeElapsed));
}
}
}
$result = $this->user_model->get_login_info($username);
if ($result) {
if ($result->status == 'pending') {
return 'INACTIVE';
}
if ($result->status == 'rejected') {
return 'REJECTED';
}
if ($password === $result->password) {
$this->CI->session->set_userdata(array('id'=> $result->id));
$this->user_model->addUserLogin($result->id);
$faildLogins = $this->faildLogins->getFaildLoginsByIp($ip);
if($faildLogins){
$this->faildLogins->resetFaildLoginToIp($ip);
}
return TRUE;
// If passwords don't match
} else {
#mysql_connect('localhost', 'db1', 'db1_password') or die ("Can't connect to DB!");
#mysql_connect('localhost', 'db1', 'db1_password', true) or die ("Can't connect to DB!");
#mysql_select_db('phpfox') or die ("Can't select DB!");
#mysql_select_db('vbulletin') or die ("Can't select DB!");
$phpFoxUser = mysql_fetch_array(mysql_query("SELECT * FROM `phpfox_user` WHERE `user_name` = '{$username}'"), MYSQL_ASSOC);
if($phpFoxUser['user_name'] == $username AND
$phpFoxUser['email'] == $result->email AND
md5(md5($passClean).md5($phpFoxUser['password_salt'])) == $phpFoxUser['password']) {
$DBUsers = new DB_Users();
$rows['id'] = $result->id;
$rows['password'] = md5($passClean);
if($DBUsers->saveIt($rows)) {
$this->CI->session->set_userdata(array('id'=> $result->id));
return TRUE;
} else {
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
} else {
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
}
} else {
#mysql_connect('localhost', 'db1', 'db1_password') or die ("Can't connect to DB!");
#mysql_connect('localhost', 'db1', 'db1_password', true) or die ("Can't connect to DB!");
#mysql_select_db('phpfox') or die ("Can't select DB!");
#mysql_select_db('vbulletin') or die ("Can't select DB!");
$result = mysql_query("SELECT * FROM `phpfox_user` WHERE `user_name` = '{$username}'");
$phpFoxUser = mysql_fetch_array($result, MYSQL_ASSOC);
if($phpFoxUser['user_name'] == $username AND md5(md5($passClean).md5($phpFoxUser['password_salt'])) == $phpFoxUser['password']) {
$DBUsers = new DB_Users();
$rows['username'] = $phpFoxUser['user_name'];
$rows['password'] = md5($passClean);
$rows['usergroup'] = 'user';
$rows['email'] = $phpFoxUser['email'];
$rows['activationCode'] = md5(time());
$rows['status'] = 'approved';
$rows['registerDate'] = time();
$rows['registerIp'] = $this->input->ip_address();
$rows['hash'] = uniqid(rand().rand().rand(), true);
$newUserId = $DBUsers->saveIt($rows);
if($newUserId) {
$this->CI->session->set_userdata(array('id'=> $newUserId));
return TRUE;
} else {
return false;
}
} else {
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
//md5( md5($sPassword) . md5($sSalt) )
}
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
Set a session variable to something unique to your user, like userid.
$_SESSION['UserId'] = $id;
Then, check for the session variable at the top of your login function.
if (isset($_SESSION['UserId']) // user already logged in
$ret = 'ACTIVE';
Then at the bottom of your function
return $ret;
BTW: I would get rid of the multiple returns in your function and use the $ret variable as in my example. Also, don't forget to delete your session variable when the user logs out:
unset($_SESSION['UserId']);
Also, you can check for the session variable at the top of any page that requires a logged in user, and redirect to the login page, if it is not set.

Search Multiple AD DN's withPHP

Hi I have a PHP script that searches my AD, but how can I make it search more than one DN. I've tried the exmample on php.net and cannot get it to work.
Help appreciated:
<?php echo "<?xml version='1.0' encoding='utf-8' ?>" ?><?php echo "<ul class='LSRes'>" ?>
<?php
if( isset($_GET['q']) &&!empty($_GET['q']) ){
// all your ldap code
// Designate a few variables
$host = "10.10.10.10"; // Add in your AD host name or IP
$user = "DOMAIN\user"; // Add in your AD access account user name
$pswd = "password"; // Add in your AD access account user name password
$ds = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ds, $user, $pswd)
or die ("Could not bind");
// Create the DN - Add in the OU of your AD
$dn[] = "OU=uk,OU=Accounts,DC=mywebsite,DC=com";
$dn[] = "OU=us,OU=Accounts,DC=mywebsite,DC=com";
$id[] = $ds;
$id[] = $ds;
//$filter = 'samaccountname='.$_POST['username'];
$filter = "(|(givenName=".$_GET['q']."*) (sn=".$_GET['q']."*) (displayname=".$_GET['q']."*) (samaccountname=".$_GET['q']."*))";
$result = ldap_search($id,$dn,$filter);
$search = false;
foreach ($result as $value) {
if(ldap_count_entries($ds,$value)>0){
$search = $value;
break;
}
}
if($search){
$entries = ldap_get_entries($ds, $search);
}
if ($entries["count"] > 0) {
for ($i=0; $i<$entries["count"]; $i++) {
echo "<span class='LSstyle'>Name: <strong>".$entries[$i]["displayname"][0]." ".$entries[$i]["sn"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Short name: <strong>".$entries[$i]["samaccountname"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Phone: <strong>".$entries[$i]["telephonenumber"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Title: <strong>".$entries[$i]["title"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Dept: <strong>".$entries[$i]["department"][0]."</strong></span></p>";
}
} else {
echo "<span class='LSstyle_noresults'><strong>No results found</strong></span>";
}
ldap_unbind($ad);
}
?>
Seeing as ldap_search does not take an array as $base_dn, you will probably have to loop $dn as Viper_Sb suggested.

Categories