List AD Group Members With PHP and LDAP - php

I am attempting to list group members for groups in a certain OU in Active Directory using PHP and LDAP. For the most part this works but if a user is from another domain, it won't pick up on them. Below is the most basic attempt I have tried. I have tried other code examples as well. With debugging turned on to 7, I see it binding to say the Asia domain and I can see the DN of the user in the error_log but it doesn't return in php.
<?php
//LDAP server address
$LDAP_Server = "ldap://americas.ad.company.com";
//AD User to use
$LDAP_User = "username#americas.ad.company.com";
//AD User Password
$LDAP_Password = "Password";
//FQDN path where search will be performed. OU - organizational unit / DC - domain component
$LDAP_DN = "OU=SITE,OU=US,DC=americas,DC=ad,DC=company,DC=com";
$LDAP_Search_String = "(&(objectCategory=person)(objectClass=user)(memberof=CN=SITE-UG-Group-M,OU=FileServer,OU=Groups,OU=SITE,OU=US,DC=americas,DC=ad,DC=company,DC=com))";
// connecting to LDAP server
$LDAP_Connection = ldap_connect($LDAP_Server);
$LDAP_Bind = ldap_bind($LDAP_Connection, $LDAP_User , $LDAP_Password);
ldap_set_option($LDAP_Connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($LDAP_Connection, LDAP_OPT_REFERRALS, 0);
// performing search
$LDAP_Search = ldap_search($LDAP_Connection, $LDAP_DN, $LDAP_Search_String);
// Sort the results based on description
ldap_sort($LDAP_Connection, $LDAP_Search, 'samaccountname');
$LDAP_Data = ldap_get_entries($LDAP_Connection, $LDAP_Search);
echo "Found " . $LDAP_Data["count"] . " members<br><br>";
for ($i=0; $i<$LDAP_Data["count"]; $i++) {
echo $LDAP_Data[$i]["dn"] . "<br>" . $LDAP_Data[$i]["cn"][0] . "<br>";
}
?>

Related

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

LDAP PHP Authentication across multiple AD Domains

Firstly, Id like to state that my PHP/LDAP skillset is minimal so am looking for a sudo genius to help me solve this issue.
Having recently merged with another company, the business wants us to allow our users to authenticate against a PHP web application in another Active Directory domain that we have a forest trust with.
Below is the code I've been given for the LDAP connection and the previous person who was a PHP genius has now left the company and this has been lumped onto me to work out. The code is however not working. The users in domain where the PHP application is store are able to access correctly.
<?php
$browser_shortname = explode('\\', $_SERVER['AUTH_USER']);
// Generate the global LDAP connection to the specificed primary server.
$ldap_connection = ldap_connect($ldap_protocol.$ldap_primaryhost) or die( header('Location: /error/?e=LD01'));
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, $ldap_protocolversion);
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, $ldap_referrals);
if ($ldap_tls == 1) {
ldap_start_tls($ldap_connection);
}
if ($ldap_debug == 1) {
ldap_set_option($ldap_connection, LDAP_OPT_DEBUG_LEVEL, 7);
}
$ldap_binding = ldap_bind($ldap_connection, $ldap_domain.'\\'.$ldap_username, $ldap_password);
if (!$ldap_binding) {
include ('/core/styles/'.$theme_selected.'/templates/101.tpl');
die();
}
$ldapus_filter = "(sAMAccountName=$browser_shortname[1])";
$ldapus_result = ldap_search($ldap_connection, $ldap_dn, $ldapus_filter);
$ldapus_details = ldap_get_entries($ldap_connection, $ldapus_result);
if ($browser_shortname[0] == "MY-DOMAIN") {
$ldap_khaconnection = ldap_connect($ldap_protocol.$ldap_khahost) or die( header('Location: /error/?e=LD01'));
ldap_set_option($ldap_khaconnection, LDAP_OPT_PROTOCOL_VERSION, $ldap_protocolversion);
ldap_set_option($ldap_khaconnection, LDAP_OPT_REFERRALS, $ldap_referrals);
$ldapus_filter = "(sAMAccountName=$browser_shortname[1])";
$ldapus_result = ldap_search($ldap_khaconnection, $ldap_khadn, $ldapus_filter);
$ldapus_details = ldap_get_entries($ldap_khaconnection, $ldapus_result);
echo "This confirms the user is coming from KHA.";
echo $browser_shortname[1];
}
$ldap_userfullname = $ldapus_details[0]["displayname"][0];
$ldap_userfirstname = $ldapus_details[0]["givenname"][0];
$ldap_usertitle = $ldapus_details[0]["title"][0];
$ldap_accountname = $ldapus_details[0]["samaccountname"][0];
?>

PHP - LDAP Authentication and Search

I am using an Online LDAP Test Server here: http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/ to test some basic LDAP code.
I need to authenticate a user and retrieve some user information.
If I understand the information about the test server correctly I should be able to bind with users that belong to respective groups. With the code 'AS IS' below I can bind to un-commented $dn, but if I use any other $dn to authenticate, the bind fails.
What am I not understanding?
For example, tesla should belong to 'ou=scientists,dc=example,dc=com' but I am unable to authenticate tesla on that DN and subsequently I can't search for related information.
$dn = 'dc=example,dc=com';
// $dn = 'ou=mathematicians,dc=example,dc=com';
// $dn = 'ou=scientists,dc=example,dc=com';
$username = 'tesla';
$password = 'password';
$filter = "(uid=" . $username . ")";
$ldapDN = 'uid=' . $username . ',' . $dn;
$ldapCONN = ldap_connect("ldap.forumsys.com") or die("Could not connect to LDAP server.");
if ($ldapCONN)
{
ldap_set_option($ldapCONN, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldapBIND = #ldap_bind($ldapCONN, $ldapDN, $password);
if ( $ldapBIND )
{
$result = ldap_search($ldapCONN, $dn, $filter) or die ("Error: ".ldap_error($ldapCONN));
$data = ldap_get_entries($ldapCONN, $result);
echo '<pre>';
print_r($data);
echo '</pre>';
}
else
{
echo "LDAP bind failed...";
}
}
When using LDAP, it is important to visualize how the database is organized.
Basically, all users are in the main folder. Use this folder to authenticate your user with, otherwise it will not work.
In this case the main folder where all users are in, is dc=example,dc=com. However, most LDAP servers use a main folder like cn=users,dc=example,dc=com.
Why are they using folders at all then? Well, that is to make it easier to categorize and search with a filter. For example, if you want to only show the names of scientists, you add the group Scientists to your search filter like $filter = "(ou=Scientists)". A filter for both groups would look like this: $filter = "(&(ou=Scientists)(ou=Mathematicians)". Now the server will take a look into this folder/these folders, and display just these members.
Hope this helps, for gaining further insight in how the server is organized, I can recommend installing Apache Directory Studio. It is free to download from their site, helped me a lot!

LDAP - List groups

I need to list all groups within a certain group using PHP. This is what I have so far:
<?php
$ldap_dn = "ou=People,dc=something,dc=something,dc=something,dc=au";
$ldap_svr = "ldap.server.somewhere";
$ldap_domain = "domain.somewhere";
$conn=ldap_connect($ldap_svr) or die("Cannot connect to LDAP server!");
ldap_set_option ($conn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($conn,"user#domain.somewhere","password");
$filter ="(ou=*)";
$justthese = array("ou");
$result=ldap_list($conn, $ldap_dn, $filter, $justthese) or die("No search data found.");
$info = ldap_get_entries($conn, $result);
for ($i=0; $i < $info["count"]; $i++) {
echo $info[$i]["ou"][0] . '<br />';
}
?>
This returns a list of groups, one of whch is 'Students', but I want to list all groups within 'Students'. How can I do this?
EDIT
Thanks to Fluffeh the Microsoft LDAP plugin allows me to search active directorys so I can tailor my PHP script accordingly, e.g. $ldap_dn = "ou=Units,ou=Groups,dc=somewhere,dc=somewher,dc=somewhere,dc=au";
So my mostly working code is:
<?php
$ldap_dn = "ou=Units,ou=Groups,dc=somewhere,dc=somewher,dc=somewhere,dc=au";
$ldap_svr = "ldap.server.somewhere";
$ldap_domain = "domain.somewhere";
$conn=ldap_connect($ldap_svr) or die("Cannot connect to LDAP server!");
ldap_set_option ($conn, LDAP_OPT_REFERRALS, 0);
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($conn,"user#domain.somewhere","password");
$filter ="(cn=*)";
$justthese = array('cn');
$result=ldap_list($conn, $ldap_dn, $filter, $justthese) or die("No search data found.");
$info = ldap_get_entries($conn, $result);
for ($i=0; $i < $info["count"]; $i++) {
echo $info[$i]["cn"][0] . '<br />';
}
?>
You need to actually pass the search to it. Currently you are using:
$filter ="(ou=*)";
This will need to change to contain 'Students'. While I am no LDAP expert, I would guess at the following:
$filter ="(cn=Students)";
Most of the LDAP stuff I have done has been sheer trial and error rather than knowing what I am doing, but this might put you on the right path.
There is also a Microsoft plugin - Active Directory Explorer you can use to at least browse the LDAP so that you know what to search for and under what branch.

Categories