LDAP issue, ldap_bind invalid dn syntax - php

I know that my mistake is going to be something really simple but I have tried to find the problem and I do not see it, maybe you can help me....
I am trying to create a function with php, so I can be able to connect to LDAP and find the desired information.
My php code is the following:
$ldapconfig['host'] = "127.0.0.1";
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = "dc=example,dc=com";
$ldapconfig['binddn'] = "user";
$ldapconfig['bindpw'] = "password";
function ldap_authenticate($user, $pass) {
global $ldapconfig;
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
if ($user != "" && $pass != "") {
$ds=ldap_connect($ldapconfig['host'],$ldapconfig['port']);
if(!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
return NULL;
}
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_bind( $ds, $ldapconfig['binddn'], $ldapconfig['bindpw']);
$r = ldap_search( $ds, $ldapconfig['basedn'], 'sAMAccountName=' . $user);
if ($r) {
$result = ldap_get_entries( $ds, $r);
if ($result[0]) {
if (ldap_bind( $ds, $result[0]['dn'], $pass) ) {
return $result[0]['mail'][0];
}
}
}
}
return NULL;
When I try to run the code it gives me the following mistake:
ldap_bind invalid DN syntax on line xxxx
and that line is the following:
ldap_bind( $ds, $ldapconfig['binddn'], $ldapconfig['bindpw']);

As stated in the error, your bind DN is the wrong format. DN's represent the full path to the object - so in your case should be something like this (looks like you're on AD?)
"cn=username,ou=domain users,dc=example,dc=com"
Depending on your flavor of LDAP (Active Directory, OpenLDAP etc), you might be able to use a uid (so just 'username') to bind, but it's best to assume that you always need the full DN.
You can use an LDAP tool like Apache Directory Studio to help build queries and find out what object's DN's are. Or there's ldp.exe too (provided it's AD), but directory studio is easier to use.

On a DC, Executing:
dsquery user -samid jim
will reveal the DN of the user matching the sAMAccountName:
"CN=Jim Willeke,CN=Users,DC=mad,DC=willeke,DC=com"
http://ldapwiki.willeke.com/wiki/LDAP%20and%20Active%20Directory

Related

Php ldap bind - Unable to bind to server: Invalid credentials

I have checked tons of solutions for this problem and yet none of them solved my problem, I am building a laravel app and need to authenticate users against AD for that purpose I found that I can accomplish this with the following script
$ldap_dn = "uid=user,dc=example,dc=local";
$ldap_password = "somePassword";
$ldap_con = ldap_connect("ldap://domain") or die("Could not connect to LDAP server.");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_con, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ldap_con, $ldap_dn, $ldap_password);
if($bind)
{
return "Authenticated";
}
However, I keep getting the same error, no matter how I change my parameters. Here's a list of things I've tried:
modifying this line $ldap_dn = "uid=user,dc=example,dc=local"; to:
$ldap_dn = "cn=user,dc=example,dc=local";
$ldap_dn = "uid=domain\user,dc=example,dc=local";
$ldap_dn = "sAMAccountName=user,dc=example,dc=local";
I am sure my credentials are correct, I have tested this in C# and it works perfectly with the following script:
public static bool IsAuthenticated(string ldap, string usr, string pwd)
{
bool authenticated = false;
try
{
DirectoryEntry entry = new DirectoryEntry(ldap, usr, pwd);
object nativeObject = entry.NativeObject;
authenticated = true;
}
catch (DirectoryServicesCOMException cex)
{
}
catch (Exception ex)
{
}
return authenticated;
}
I even tried compiling a c# dll to bypass ldap binding in php but got to a dead-end with that solution too...

ldap_add(): Add: Referral

I'm trying to add the user to my LDAP server. But I'm getting the below error.
PHP Warning: ldap_add(): Add: Referral
Code:
$ds = ldap_connect("HOST","PORT");
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ds, "adminusername", "Passwrd");
echo $bind;
// prepare data
$base_dn = 'CN=Manus Test,OU=UserAccounts,DC=rk.com,DC=rk';
$info["givenName"]="manu";
$info["sn"]="Manu";
$info["uid"]="manus";
$info["homeDirectory"]="/home/";
$info["mail"]="manus#gmail.com";
$info["displayName"]= "Jdkd sjs";
$info["cn"] ="Manus Test";
//$info["userPassword"]=>user_hash;
$info["objectclass"][0] = "top";
$info["objectclass"][1] = "person";
$info["objectclass"][2] = "inetOrgPerson";
$info["objectclass"][3] = "organizationalPerson";
// add data to directory
$r = ldap_add($ds, $base_dn, $info);
echo "Bind result is " . $r . "<br />";
Please let me know any suggestions.
Referrals can be returned if you are talking to a slave LDAP server (essentially a read-only copy of the directory). If you know you are talking to a server hosting a writable copy of the replica, referrals are also returned when the DN base is not something hosted by that server.
Looking at the code above, "DC=rk.com,DC=rk" is unusual. I generally see the "domain" components broken out so rk.com becomes "dc=rk,dc=com". Use an ldap browser to verify the pattern for fully qualified DNs in your directory.

Invalid DN syntax on LDAP Authentication

I know this has sort of been answered before but it hasnt been able to help me (unless it has but because of my limited php knowledge it hasn't helped). Here is my code below:
<body>
<html>
<?php
//echo var_dump($_POST);
$user = "".$_POST["username"]."";
settype($user, "string");
$password = $_POST["password"];
$ldap_host = "ldap.burnside.school.nz";
$base_dn = "ou=students,o=bhs";
$ldap_user = "(cn=".$user.")";
$filter = "($ldap_user)"; // Just results for this user
$ldap_pass = "".$password."";
$connect = ldap_connect($ldap_host)
or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
// This next bit is the important step. Bind, or fail to bind. This tests the username/password.
if (ldap_bind($connect, $ldap_user.",".$base_dn, $ldap_pass)) {
$read = ldap_search($connect, $base_dn, $filter)
or exit(">>Unable to search ldap server<<");
// All the next 8 lines do is get the users first name. Not required
$info = ldap_get_entries($connect, $read);
$ii = 0;
for ($i = 0; $ii < $info[$i]["count"]; $ii++) {
$data = $info[$i][$ii];
if ($data == "givenname") {
$name = $info[$i][$data][0];
}
}
ldap_close($connect);
header("Location: success.php?name=$name");
}
else {
ldap_close($connect);
//header("Location: failure.php?user=$user");
}
?>
</body>
</html>
I am getting an error on line 21 which is when I bind to the server saying:
Warning: ldap_bind(): Unable to bind to server: Invalid DN syntax in S:\XAMPP\htdocs\PhpProject1\LDAP_main.php on line 21
Would anyone have a solution to this problem? It has only started happening when I implemented my $_POST into the code to receive the username and password but as you can see with my commented out // echo var_dump($_POST) I am actually receiving the data I want.
Your DN for binding to the LDAP-Server is (cn=[username]),ou=students,o=bhs which is not a valid DN-Syntax. That should read cn=[username],ou=students,o=bhs without the braces.
You have mixed up an LDAP-Filter (the stuff inside the braces) with a DN.
I'd do an LDAP authentication in the following way:
Bind anonymously or with a default user where you know the DN
Use that user to do a search for all users that match a certain filter that contains the provided username. you can use a filter like (|(mail=[username])(cn=[username])(uid=[username])) to look for entries that have the username in the mail, cn or uid-attribute
Get the DN from the returned Entry (if there are no or more than one entry there is no appropriate user existent so we can skip the rest)
bind to the ldap again with that retreived DN and the provided password.
Have a look at https://gist.github.com/heiglandreas/5689592

php Active Directory lookup

I am trying to do an ldap authorization and then a secondary check for membership in a group. System is an Ubuntu machine running php 5.3.10 authenticating against a Server2008 R2 Active Directory. I can't seem to get ldap_search() to work. I have pulled the DN from jExplore so I am pretty sure the DN is correct. ldap_bind works (in another function) with the credentials so I am sure the server and the username/password are valid. The error:
PHP Warning: ldap_search(): Search: Operations error in /var/www/zzz.php on line 28
The code:
$ldap = ldap_connect('ldap://xxx.xxx');
$admins = $auth['admin'];
// User not logged in, user level '0'
if (!isset($user))
{
return 0;
}
// DN
$group_dn = 'CN=IT Employees,OU=groups,OU=users,OU=xxx,DC=xxx,DC=xxx';
// Filter
$filter = '(sAMAccountName=' . $user . ')';
// Attributes
$attr = array("memberof","givenname");
echo $group_dn.' '.$filter.' '.$attr.'<br />';
// Check if the user is a member of the Admin Group
$SubGroups = ldap_search($ldap, $group_dn, $filter, $attr); //Search the admin group for user.
$debug = ldap_get_entries($ldap, $SubGroups);
echo $debug['count'];
if ($debug['count']>>0)
{
// Yep, you are set admin. (User level 2)
echo "Admin Set<br />";
return 2;
}
else
{
// Failure. Thou art a normal user. (User level 1)
echo "Admin Denied<br />";
return 1;
}
}
$ldap = ldap_connect('ldap://xxx.xxx');
needed to change to
$ldap = ldap_connect('ldap://xxx.xxx');
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_start_tls($ldap);
$bind= ldap_bind($ldap, 'user','pass');
I think this filter should work:
(&(objectClass=user)(sAMAccountName=yourUserName)
(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))
Well I am sure this could be tuned to work for you.
-jim

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