LDAP insert new user - php

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!

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...

Set password when creating a new Active Directory user account in PHP

This PHP script creates enabled user accounts in Active Directory without a password. How do I set the password?
<?php
$examplePassword = "34mlrfm$sxkf";
$WinTimestamp = "131196672000000000" //30-09-16 00:00:00
//Create unicode password
function encodePassword($password) {
$password="\"".$password."\"";
$encoded="";
for ($i=0; $i <strlen($password); $i++){ $encoded.="{$password{$i}}\000";}
return $encoded;
}
//Build Active Directory record
$ldaprecord["accountExpires"] = $winTimestamp;
$ldaprecord["UserAccountControl"] = "544"; //544 - Account enabled, require password change
$ldaprecord['userPassword'] = encodePassword($examplePassword);
$ldaprecoed['otherAttributes'] = "Truncated from question";
$ds = ldap_connect($AD_server); // Connect to Active Directory
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$r = ldap_bind($ds, $AD_Auth_User, $AD_Auth_PWD); //Bind
$r = ldap_add($ds,$dn,$ldaprecord); //Create account
ldap_close($ds); //Close connection
}
?>
I've tried different password encoding methoods.
I've also tried inserting the password into $ldaprecord["unicodepwd"]. Which results in "Server is unwilling to perform" error.
I've got it working. You can only set passwords over an SSL connection, thanks #stuartbrand
Either encrypt traffic on 389 using ldap_start_tls() or connect on 636 using $ds = ldap_connect('ldaps://'.$AD_server);
Password should be inserted into the $ldaprecord["unicodepwd"] attribute.

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 LDAP binding AD with the server's user account

I have some code that uses PHP and LDAP to connect to AD:
$host = 'ldap://stack.overflow.com';
$port = 389;
$username = 'stackOverflow';
$password = 'IaMP4ssWord';
$dn = 'CN=Users, DC=STACK, DC=OVERFLOW, DC=COM';
$cond = '(&(objectcategory=user)(displayname=*))';//All users that have a displayname
if($ldap = ldap_connect($host, $port))
{
if(ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3))
{
if(ldap_bind($ldap, $username, $password))
{
$attrs = array('displayname', 'mail');
if($rs = ldap_search($ldap, $dn, $cond, $attrs))
{
$results = ldap_get_entries($ldap, $rs);
echo "<pre>";print_r($result);echo "</pre>";//Print the results
}
}
else
{ echo 'Binding failed';}
}
else
{ echo 'Setting options failed';}
}
else
{ echo 'Connection failed'; }
Now this code works just fine. It print out every user that has a displayname in AD.
Problem is for the username/password binding i am using my own user credential to bind to the server.
I would like to know if there is a way to bind using the servers credentials.
I am setup using PHP 5.3 + IIS on windows server 2008 R2 for both the server with IIS and the one that has AD.(two different VM).
I also know that IIS has a AD account named IISStackOverflow but I don't know the password or even if it has a password...
Thanks!
Oh! I tried changing $username to IISStackOverflow and $password to ''
But it gave invalid credential error.
--EDIT--
Do I have to do the binding part at all? (If I am only reading data)
As you run it from server itself, and you just want to read I would try to use :
...
if(ldap_bind($ldap))
...
According to PHP documentation if bind_rdn and bind_password are not specified, an anonymous bind is attempted.
Then if your anonymous logon is refused (this should not be, because running under IIS on the server your code is at least executed as a domain user) you will find there how to enable anonymous LDAP binds to Windows Server. This used to work forme on W2K8, Inever test it on W2K12.

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