Invalid DN syntax on LDAP Authentication - php

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

Related

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_list() Bad search filter

I'm trying to list my Active Directory users using PHP ldap_list() function. I get the following errors when I execute the php code.
LDAP bind successful... Warning: ldap_list(): Search: Bad search filter in /var/www/html/ldapn.php on line 29
Below is my PHP Code:
<?php
// using ldap bind
$ldaprdn = 'draven#myserver.com'; // ldap rdn or dn
$ldappass = 'draven678'; // associated password
// connect to ldap server
$ldapconn = ldap_connect("dc.myserver.com")
or die("Could not connect to LDAP server.");
if ($ldapconn) {
// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);
// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}
$basedn = "dc=myserver, dc=com";
$justthese = array("OU_Test");
$sr = ldap_list($ldapconn, $basedn, "OU_Test=*", $justthese);
}
?>
note : OU_Test is an Organizational unit. My requirement is to list all users in that Organizational Unit.
What's wrong with my code? How will I be able to resolve this error?
To list all users in the Organizational Unit 'OU_TEST' with ldap_list() :
Use the appropriate $basedn. It should be the distinguished name of 'OU_TEST' since you want to list users that are INSIDE OU_TEST. You can get it with ldap_search().
Use the appropriate filter : to list only users, filter by users.
// 1. Get OU_TEST's dn. Search down the tree using a top/root dn as $basedn :
$basedn = "dc=myserver, dc=com";
// Filters usually looks like ([attributeName]=[attributeValue])
$filter = '(ou=OU_TEST)';
$sr = ldap_search($ds, $basedn, $filter);
... say we put the resulting dn in $OU_TEST_dn variable...
// 2. List users. If users are missing, use 'objectClass=organizationalPerson'
$filter = '(objectClass=Users)';
// Use the correct basedn
$basedn = $OU_TEST_dn;
// This should work
$sr = ldap_list($ldapconn, $basedn, $filter);
the filter here should be in braces:
here is how:
$sr = ldap_list($ldapconn, $basedn, "(OU_Test=*)", $justthese);
This should work just fine.
If it doesn't work
follow the example here
<?php
$ldapconfig['host'] = '10.10.10.10';
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=company,dc=com';
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);
$dn="uid=".$username.",ou=OU_TEST,".$ldapconfig['basedn'];
if ($bind=ldap_bind($ds, $dn, $password)) {
echo("Login correct");
} else {
echo("Unable to bind to server.</br>");
echo("msg:'".ldap_error($ds)."'</br>"); //check if the message isn't: Can't contact LDAP server :)
//if it say something about a cn or user then you are trying with the wrong $dn pattern i found this by looking at OpenLDAP source code :)
//we can figure out the right pattern by searching the user tree
//remember to turn on the anonymous search on the ldap server
if ($bind=ldap_bind($ds)) {
$filter = "(OU_TEST=*)";
if (!($search=#ldap_search($ds, $ldapconfig['basedn'], $filter))) {
echo("Unable to search ldap server<br>");
echo("msg:'".ldap_error($ds)."'</br>"); //check the message again
} else {
$number_returned = ldap_count_entries($ds,$search);
$info = ldap_get_entries($ds, $search);
echo "The number of entries returned is ". $number_returned."<p>";
for ($i=0; $i<$info["count"]; $i++) {
var_dump($info[$i]); //look for your user account in this pile of junk and apply the whole pattern where you build $dn to match exactly the ldap tree entry
}
}
} else {
echo("Unable to bind anonymously<br>");
echo("msg:".ldap_error($ds)."<br>");
}
}
?>
Let me know if it does not work. We will try and figure it out!

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

LDAP issue, ldap_bind invalid dn syntax

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

PHP LDAP, adding new entries into LDAP

I am wanting to create a form that I can fill out and once I submit it the form values can be pulled out and that person can be created into LDAP. I am not very experienced with LDAP infact I just worked towards making an LDAP bind work so I am needing some help. How can I add new users into LDAP through this form I can fill out? I know LDAP has an Add commands but I am not particularly sure on how to get started and what information needs to be passed for the person to be created in LDAP. If it helps, below is my code for LDAP bind.
<?php
$name=$_REQUEST['name'];
$x=1;
if($x==1)
{
//LDAP stuff here.
$username = "myusername";
$password = "mypass";
$ds = ldap_connect('ldap://ldap:389');
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
//Can't connect to LDAP.
if( !ds )
{
echo "Error in contacting the LDAP server -- contact ";
echo "technical services! (Debug 1)";
exit;
}
//Connection made -- bind anonymously and get dn for username.
$bind = #ldap_bind($ds);
//Check to make sure we're bound.
if( !bind )
{
echo "Anonymous bind to LDAP FAILED. Contact Tech Services! (Debug 2)";
exit;
}
$search = ldap_search($ds, "ou=People,DC=sde,DC=goliat,DC=com", "uid=$username");
//Make sure only ONE result was returned -- if not, they might've thrown a * into the username. Bad user!
if( ldap_count_entries($ds,$search) != 1 )
{
echo "Error processing username -- please try to login again. (Debug 3)";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
$info = ldap_get_entries($ds, $search);
//Now, try to rebind with their full dn and password.
$bind = #ldap_bind($ds, $info[0][dn], $password);
if( !$bind || !isset($bind))
{
echo "Login failed -- please try again. (Debug 4)";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
//Now verify the previous search using their credentials.
$search = ldap_search($ds, "ou=People,DC=sde,DC=goliat,DC=com", "cn=$name");
$info = ldap_get_entries($ds, $search);
if( $username == "myusername" )
{
/*
very useful set of information to view the LDAP tree info from an array
echo $username;
echo "<pre>".print_r($info[0],true)."</pre><br />";
*/
echo $info[0][cn][0];
echo ",";
echo $info[0][mail][0];
echo ",";
echo $info[0][telephonenumber][0];
exit;
}
else
{
echo "Error. Access Denied";
redirect(_WEBROOT_ . "/try1b.php");
exit;
}
ldap_close($ds);
exit;
}
?>
I would recommend a newUser.php (or whatever) file that checks to make sure that all of your required information is present, then send that info to the file you have started above.
Your $bind should take three variables...
$bind = ldap_bind($ds, 'cn=root,dc=example,dc=com', secretPassword);
For a pretty good guide to adding people to your LDAP server via PHP go to http://www.php2python.com/wiki/function.ldap-add/
Good luck
An add request requires the distinguished name to be added and the attribute that are to be part of the entry, and optional request controls.
On another subject, your search has subtree scope and may return more than one entry that matches user name. There is no reason why there could not be multiple entries with the same RDN in different branches underneath the base object specified in the code - unless your directory server vendor has implemented an attribute uniqueness constraint.

Categories