add users in microsoft active directory via php ldap_add - php

I have tried adding users via php ldap Active-Directory for Microsoft Server 2008 R2 datacenter, but I can't. I always get this error :
An error occurred. Error number 64: Naming violation
The code is:
<?php
$ldaprdn = 'administrador#correo.mx';
$ldappass = 'dir378prob#';
$ds = 'correo.mx';
$dn = 'ou=usuarios,dc=correo,dc=mx';
$puertoldap = 389;
$ldapconn = ldap_connect($ds,$puertoldap)or die("ERROR: I Don'n connect to LDAP.");
if ($ldapconn)
{
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS,0);
$con = ldap_bind($ldapconn, $ldaprdn, $ldappass);
if ($con)
{
$info["cn"] = $_POST['cn'];
$info["sn"] = $_POST['sn'];
$info["mail"] = $_POST['mail'];
$info["objectclass"] = "inetorgperson";
// prepare DN for new entry
$dn_aux = "mail=" . $_POST['mail'] . ",ou=usuarios,dc=correo,dc=mx";
$result = ldap_add($ldapconn, $dn_aux, $info);
if($result)
{
echo "New entry with DN " . $dn . " added to LDAP directory.";
}
// else display error
else
{
echo "An error occurred. Error number " . ldap_errno($conn) . ": " .
ldap_err2str(ldap_errno($conn));
}
}
else
{
echo "LDAP bind error...";
}
}
ldap_close($ldapconn);
?>
I'm taking my first steps in this ldap, so please could you explain in detail.

Not sure of the correct PHP syntax but the following line :
$dn_aux = "mail=" . $_POST['mail'] . ",ou=usuarios,dc=correo,dc=mx";
is not correct concerning an Active-Directory. The explanation is that in such a Directory your are not able to choose the attribute you use for naming an object. For example an 'InetOrgPerson' object MUST use the CN attribute to name it. For more details read carefuly naming attributes in object naming from Microsoft documentation.
try :
dn_aux = "CN=" . $_POST['cn'] . ",ou=usuarios,dc=correo,dc=mx";

Related

Place check on Active Directory user fields using PHP

I am creating a user in Active Directory using PHP and create it correctly, but now I need to check the options shown in the image from the same PHP code, I also attach an example of how the user created in Active Directory using PHP.
Checks that I need to do using PHP
User creation code
<?php
// Username used to connect to the server
$username = "administrator";
// Password of the user.
$password = "Password01";
// Domain used to connect to.
$domain = "nagara.ca";
// Proper username to connect with.
$domain_username = "$username" . "#" . $domain;
// User directory. Such as all users are placed in
// the Users directory by default.
$user_dir = "OU=Students,DC=nagara,DC=ca";
// Either an IP or a domain.
$ldap_server = "192.168.100.2";
// Get a connection
$ldap_conn = ldap_connect($ldap_server);
// Set LDAP_OPT_PROTOCOL_VERSION to 3
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("Could not set LDAP Protocol version");
// Authenticate the user and link the resource_id with
// the authentication.
if($ldapbind = ldap_bind($ldap_conn, $domain_username, $password) == true)
{
// Setup the data that will be used to create the user
// This is in the form of a multi-dimensional
// array that will be passed to AD to insert.
$adduserAD["cn"] = "testuser";
$adduserAD["givenname"] = "Test";
$adduserAD["sn"] = "User";
$adduserAD["sAMAccountName"] = "testuser";
$adduserAD['userPrincipalName'] = "testuser#nagara.ca";
$adduserAD["objectClass"] = "user";
$adduserAD["displayname"] = "Test User";
$adduserAD["userPassword"] = "Password01";
$adduserAD["userAccountControl"] = "544";
$base_dn = "cn=testuser,ou=students,DC=nagara,DC=ca";
// Attempt to add the user with ldap_add()
if(ldap_add($ldap_conn, $base_dn, $adduserAD) == true)
{
// The user is added and should be ready to be logged
// in to the domain.
echo "User added!<br>";
}else{
// This error message will be displayed if the user
// was not able to be added to the AD structure.
echo "Sorry, the user was not added.<br>Error Number: ";
echo ldap_errno($ldap_conn) . "<br />Error Description: ";
echo ldap_error($ldap_conn) . "<br />";
}
}else{
echo "Could not bind to the server. Check the username/password.<br />";
echo "Server Response:"
// Error number.
. "<br />Error Number: " . ldap_errno($ldap_conn)
// Error description.
. "<br />Description: " . ldap_error($ldap_conn);
}
// Always make sure you close the server after
// your script is finished.
ldap_close($ldap_conn);
?>
I hope you can support me.
Thank you very much.

login PHP to Active Directory Fail

I am trying to verify the authentication of a user through a simple PHP code but I always get the same error "Invalid credentials ".
$ldap_dn = "uid=".$_POST["username"].",DC=xxx,DC=xxx,DC=xxx,DC=xxx,DC=xxx";
$ldap_password = $_POST["password"];
$ldap_con = ldap_connect("xxx", 389);
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION,3);
//check connection
if ($ldap_con === FALSE) {
die("<p> Couldn't connect to LDAP service </p>");
} else {
echo "<p> connessione avvenuta con successo </p>";
}
// check authentication
if(#ldap_bind($ldap_con, $ldap_dn, $ldap_password)){
echo "Autenticato";
}else{
echo "Autenticazione Fallita <br>";
echo ldap_error($ldap_con);
}
PHP code runs on XAMP on a PC W7pro already logged into the company domain.
I have obtained the AD address from the same machine on which I perform the tests; for retrive DN I've used the program "Softerra LDAP browser", but actually I'm not sure for this parameter.
When a user logs on to the domain, the username uses three letters of the surname followed by two of the name, e.g. Name = Alfred / Surname = Pecora username = pecal.
Does $ldap_dn in your code match the DN in AD properly?
If you are administrator for the AD, you can confirm it by executing dsquery command on DOS prompt on the AD.
e.g.,
dsquery user -name pecal
Or you can use the format <name>#<domain> instead of DN format:
$ldap_dn = $_POST["username"]."#example.com";
I ran a new test:
$adServer = "xxx";
$ldap = ldap_connect($adServer,389);
$username = $_POST['username'];
$password = $_POST['password'];
$ldapRdnLogin = "CN=MyName MySurname,OU=CED,OU=Users,DC=intranet,DC=xxx,DC=xxx,DC=xx,DC=it";
$ldapRdn = "OU=Users,DC=intranet,DC=xxx,DC=xxx,DC=xx,DC=it";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
$bind = #ldap_bind($ldap, $ldapRdnLogin, $password);
if ($bind) {
$filter="(sAMAccountName=$username)";
$result = ldap_search($ldap,$ldapRdn,$filter);
ldap_sort($ldap,$result,"sn");
$info = ldap_get_entries($ldap, $result);
for ($i=0; $i<$info["count"]; $i++)
{
if($info['count'] > 1)
break;
echo "<p>You are accessing <strong> ". $info[$i]["sn"][0] .", " . $info[$i]["givenname"][0] ."</strong><br /> (" . $info[$i]["samaccountname"][0] .")</p>\n";
echo '<pre>';
var_dump($info);
echo '</pre>';
$userDn = $info[$i]["distinguishedname"][0];
}
#ldap_close($ldap);
} else {
$msg = ldap_error($ldap);
echo $msg;
}
In the above example the binding "MyName MySurname" \ DN works and I can perform the search.
I think that the problem is to find the right DN to bind with sAMAccountName

LDAP insert new user

I have windows server 2012 and i want to insert new user using ldap and php
the connection to ldap server is ok but I can not insert new user
and I have more than one error every time I change the dn code
the last error I have is
Warning: ldap_add(): Add: Naming violation in C:\AppServ\www\auth\insert.php on line 36
the code of my php file is
<?php
$ip = "10.10.10.35:389";
$ldap_url = "ldap://$ip";
$ldaps_url = "ldaps://$ip";
$ldap_domain = 'peace.world';
$ldap_dn = "dc=peace,dc=world";
$ldap_conn = ldap_connect($ldap_url)
or die("Could not connect to LDAP server ($ldap_url)");
echo $ldap_con;
if ($ldap_conn)
echo " connected";
$username = "captiveportal";
$password = "123";
$result = ldap_bind($ldap_conn, "$username#$ldap_domain", $password)
or die("<br>Error: Couldn't bind to server using supplied credentials!");
if ($result) {
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
$dn = "cn=Users,DC=peace,DC=world";
echo $dn;
$info["cn"] = "muh Jones";
$info["sn"] = "muh";
$info["objectclass"] = "person";
try {
## Heading ##
$r = ldap_add($ldap_conn, $dn, $info);//36 line the error is here
--------------------------------------
}
catch (Exception $e) {
echo $e;
}
} else
echo "cannot connect to ldap";
the image of my active directorty users and computers is enter image description here
You do indeed have a naming violation. You are trying to add a new entry with DN "cn=Users,dc=Peace,=dc=world" but that DN is already taken as it's the DN of the entry that holds all users. You most likely want to add a DN "cn=muh Jones,cn=Users,dc=Peace,dc=world"
Besides that there are probably some attributes missing like f.e. samaccountname but thats most likely not what causes your error.
Additionally I'd recommend to set the Protocol version right after the ldap_connect!

PHP ldap_get_entries() return count=zero

I am trying to authenticate users' login against LDAP(Server is Mac El Capitan).
I can successfully connect and bind to the ldap server.
I can search and sort the result.
But when I perform "ldap_get_entries",I received "Zero" entry.
I've tried everything from StackOverFlow to Google's second page.
Any Suggestions or idea why this might be happening?
MY CODE -
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$usernameLogin=$_POST['email'];
$passwordLogin=$_POST['password'];
$username = stripslashes($usernameLogin);
$password = stripslashes($passwordLogin);
echo "User name is ".$username;
echo "</br>";
$ldapUser = "uid=xxxxxx,cn=users,dc=dns1,dc=xxxxxxxx,dc=com";
$ldapPass = "xxxxxxxxxxx";
$url = "ldap://dns1.xxxxxxx.com:389";
$ldap = ldap_connect("$url") or die("Could not connect to LDAP server.");
$baseDN = "cn=users,dc=dns1,dc=xxxxxxxxx,dc=com";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS,0);
$bind = ldap_bind($ldap, $ldapUser, $ldapPass);
if($bind) {
echo "Connected To LDAP";
echo "</br>";
$filter="(sAMAccountName=$username)";
echo "Filter = ".$filter;
echo "</br>";
$result = ldap_search($ldap,$baseDN,$filter) or die("Could not search.");
echo "Result = ".$result;
echo "</br>";
$sort = ldap_sort($ldap,$result,"uid");
echo "Sort = ".$sort;
echo "</br>";
$number = ldap_count_entries($ldap, $result);
echo "Count Entries = ".$number;
echo "</br>";
$info = ldap_get_entries($ldap, $result);
echo "Data for " . $info["count"] . " items returned:<p>";
echo "Info = ".$info;
echo "</br>";
echo '<pre>'; print_r($info); echo '</pre>';
echo "</br>";
$fentry= ldap_first_entry($ldap, $result);
echo "First Entry = ".$fentry;
for ($i=0; $i<$info["count"]; $i++)
{
if($info['count'] > 1)
break;
echo "<p>You are accessing <strong> ". $info[$i]["sn"][0] .", " . $info[$i]["givenname"][0] ."</strong><br /> (" . $info[$i]["samaccountname"][0] .")</p>\n";
echo '<pre>';
var_dump($info);
echo '</pre>';
$userDn = $info[$i]["distinguishedname"][0];
}
ldap_close($ldap);
}
else{
echo "Cannot Connect To LDAP.";
}
}}
?>
I can connect - bind - search But "ldap_get_entries()" returns zero.
First: You can skip the or die "Could not connect to LDAP Server" as that will almost never happen. ldap_connect only checks the parameter for syntactical correctness and does not actually connect to the server. The actual connection happens on the first call to the server which usually is ldap_bind. That's why conncetion issues often surface on ldap_bind and not on ldap_connect.
Second: Where did you get samAccountName from? That's a field that's usually used by ActiveDirectory. In Apples OpenDirectory the user is usually identified by the uid-attribute. So your filter should be sprintf('uid=%s', $username).
Third: I doubt that only Users in the group "Open Directory Administrators" are allowed to bind agains the LDAP. They for sure are the only ones allowed to edit the directory but every other user can bind as well.
Fourth: ldap_sort is deprecated by now. It's not sorting on the server side but on the client side. So only the returned results are sorted. When you have paged results that means that - even though you sorted the result - there still will be entries that would fit right in between your results. I'm currently working on a way to use server-sided sorting but that relies on the feature to be available on the server. So you can use ldap_sort but you can also implement your own sorting on the result set.
So change the filter to uid=$username and you'll get the expected results. The mail attribute might also contain the full email-address and might therefore then fail! You can also adapt the filter to search more than one field. Have a look at this slide for short examples.
Solved it. I used "mail" instead of "sAMAccountName".
Here's the details -
1 ) From
$filter="(sAMAccountName=$username)";
to
$filter="(mail=$username)";
2 ) From
$sort = ldap_sort($ldap,$result,"uid");
to
$sort = ldap_sort($ldap,$result,"mail");
That's it.
Lessons learn from here -
Use "LDAP Admin Tool" or some sort of LDAP Tool to understand the structure of your LDAP environment before jumping into coding. Big lesson learnt.

php ldap_search not returning results

I'm establishing a connection to our Active Directory listing of users/employees. I've done this through .NET, but cant get it to work in my PHP app.
I consistantly get a count of 0.
I've tried using samaccountname and sAMaccountname as filters, this does not change the result.
I am successfully connecting, as changing the $ldap will no longer find the server.
I am using valid credentials, as changing $authUser or $authPath provide an authorized error message.
The ldap_bind (i presume) is working, because it does perform the search and outputs a count of 0.
Here is my code:
<?php
try{
$ldap = "vmc-dc.CompanyName.vmc";
$authUser = "vmc\\MyUsername";
$authPass = "MyPassword";
$baseDn = "dc=vmc-dc,dc=CompanyName,dc=com";
$filter="(&(objectClass=user)(samaccountname=*))";
$conn = ldap_connect($ldap, 389) ;
if ($conn) {
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);
// binding to ldap server
$ldapbind = ldap_bind($conn, $authUser, $authPass);
// verify binding
if ($ldapbind) {
//$sr=ldap_read($conn, $baseDn, $filter);
$sr=ldap_search($conn, $baseDn, $filter);
$number_returned = ldap_count_entries($conn,$sr);
echo "Count: " . $number_returned . "<br/>";
$entry = ldap_get_entries($conn, $sr);
ldap_close($conn);
echo "value = '" . $entry[0] . "'";
} else {
echo "LDAP conn ok...";
}
}
} catch (Exception $e) {
}
?>
I wonder if your filter is too broad, all user class objects (which includes computers, to Brian Desmond's point) and is returning more than 1000 found objects. In which case AD will error, and return nothing. I would expect you would get a returned error, so this may not be likely. But a more constrained filter, and/or a repetition with a standalone LDAP tool could help validate this idea.

Categories