LDAP query string get information from AD - php

I am trying to get information out of AD using LDAP query and PHP. Below is my code and it seems like nothing returns from this code. I have an issue with code block in if (TRUE === $bind). Would anyone help me to point out the error?
This is php code for listing all users in AD and showing up on WordPress page.
$ldap_password = "pass";
$ldap_username = "username";
$person = "Scott";
$ldap_connection = ldap_connect("host1");
if (FALSE === $ldap_connection) {
echo "Connection is failed<br />";
}
else {
echo "Connection is successful<br />";
}
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($ldap_connection, $ldap_username, $ldap_password);
if (TRUE === $bind) {echo "Binding is successful<br />";}
else {echo "Binding is unsuccessful<br />";}
if (TRUE === $bind) {
echo "Retrieving...<br />";
$baseDN = "dc=domain,dc=com";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array("ou");
$sr = ldap_list($ldap_connection, $baseDN, $filter, $justhese);
$info = ldap_get_entries($ldap_connection,$sr);
echo $info["count"]."Hello<br />";
for ($i=0; $i < $info["count"]; $i++) {
echo $info[$i]["ou"][0];
}
ldap_unbind($ldap_connection);
echo "Unbinding is completed<br />";
}
This is what shows up on the page
Connection is successful
Binding is successful
Retrieving…
Hello
Unbinding is completed
Thanks

Related

Create user in LDAP, authentication failed

When creating the user I cannot start the section with the user's password. The user is created, but when testing the connection, it marks invalid credentials. Can you tell me where I am wrong? How should the password be encrypted?
$ds = '192.168.1.10';
$portldap = 389;
$ldap_username = 'CN=Administrador,CN=Users,DC=Local,DC=com';
$ldap_password = 'rootadm1';
$ldap_password_user = $ldap_password;
$ldap_connection = ldap_connect($ds, $portldap);
if($ldap_connection ){
// We have to set this option for the version of Active Directory we are using.
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.
$r = ldap_bind($ldap_connection, $ldap_username, $ldap_password);
if($r === TRUE){
$CN = htmlspecialchars($_POST["cn"]);
$ldaprecord['cn'] = $CN;
$ldaprecord['sAMAccountName'] = $_POST["sAMAccountName"]; //20caract
$ldaprecord['userPrincipalName'] = $_POST["userprincipalname"];
$ldaprecord["objectClass"][0] = "top";
$ldaprecord["objectClass"][1] = "person";
$ldaprecord["objectClass"][2] = "organizationalPerson";
$ldaprecord["objectClass"][3] = "user";
$ldaprecord['description']= $_POST["description"];
$ldaprecord["userAccountControl"][0] = "66656";
$ldap_new = 'CN='.$CN.',CN=Users,DC=Local,DC=com';
$result = ldap_add($ldap_connection, $ldap_new, $ldaprecord);
if($result) {
//Success creating user - Add password
$addPrecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',md5($ldap_password_user)));
//$addPrecord["unicodePwd"][0] = iconv( 'UTF-8', 'UTF-16LE', $ldap_password_user );
$add_record= ldap_modify($ldap_connection, $ldap_new, $addPrecord);
if($add_record){
ldap_close($ldap_connection);
return $result;
}
else {
echo "LDAP Error: ".ldap_error($ldap_connection)."\n";
exit;
}
}
else {
echo "LDAP Error: ".ldap_error($ldap_connection)."\n";
exit;
}
}
}
else {
echo "cannot connect to LDAP server at $ds.";
} ```
[enter image description here][1]
[1]: https://i.stack.imgur.com/QOzqZ.png

Connect Office 365 use POP3 - PHP

I have a trouble with Office 365 use POP3 method.
Currenty, I can't connect to this server:
outlook.office365.com
port:995
This is my code example:
<?php
$host = 'outlook.office365.com';
$port = '995';
$username = 'outlook_mail';
$password ='password';
$mbox = imap_open('{'.$host.':'.$port.'/pop3/ssl/novalidate-cert}', $username, $password);
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{".$host.":".$port ."}", "*");
if ($folders == false) {
echo "Call failed<br />\n";
} else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);
if ($headers == false) {
echo "Call failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}
imap_close($mbox);
If I change port to 993, it's OK.
Anyone know this problem? Many thanks!
I think it's because pop3 is on port 993 and imap is on port 995.
Have you tried with imap in your host config instead of pop3 when using port 995 ?
$mbox = imap_open('{'.$host.':'.$port.'/imap/ssl/novalidate-cert}', $username, $password);
Source : https://www.php.net/manual/en/function.imap-open.php (flag section)

PHP LDAP Connection

I was sent the following LDAP parameters, but am not sure how to establish a connection in PHP. I'm not sure which PHP function to use with each set of parameters. Here are the parameters I was given:
Server: ldaps://the_server.com:636
root DN: dc=the_info,dc=more_info,dc=com
User search base: ou=CompanyUsers
User search filter: sAMAccountName={0}
Group search base: OU=Security,OU=CompanyGroups
Group search filter: cn={0}
Group membership: Group membership attribute = memberOf
Display Name LDAP attribute: displayname
Email Address LDAP atribute: mail
If someone could provide a php script for me that would be great! This is my first time using LDAP and still do not understand all these parameters.
Following is the working code for linux base ldap.
It might be helpful to you.
<?php
$username = 'uid=amitkawasthi,ou=CompanyUsers,dc=the_info,dc=more_info,dc=com';
$password= 'test';
$ds=ldap_connect("the_server.com, 636");
echo $ds;
if ($ds) {
echo "Binding ...";
$r=ldap_bind($ds, $username, $password);
if ($r)
{
$sr=ldap_search($ds,"ou=CompanyUsers,dc=the_info,dc=more_info,dc=com", "uid=amitkawasthi");
$entry = ldap_first_entry($ds, $sr);
$attrs = array();
$attribute = ldap_first_attribute($ds,$entry,$identifier);
while ($attribute) {
$attrs[] = $attribute;
$attribute=ldap_next_attribute($ds,$entry,$identifier);
}
echo count($attrs) . " attributes held for this entry:<p>";
$ldapResults = ldap_get_entries($ds, $sr);
//for ($item = 0; $item < $ldapResults['count']; $item++) {
// for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++) {
//echo $data = $ldapResults[$item][$attribute];
echo $data = $ldapResults[0][$attribute];
echo $data.": ".$ldapResults[0][$data][0]."<br>";
//}
///echo '<hr />';
echo "OK";
}
else
{
echo "Fail";
}
}
?>
============================

Verifying user is part of ldap/active directory security group

Ok... I've dug through the examples and etc on here and I'm still having issues.
<?php
// SHOW ERRORS 0=NO 1=YES
ini_set('display_errors', '1');
//USER
$valid_session_username = $_POST["username"];
$valid_session_password = $_POST["password"];
//MEMBER OF THIS GROUP
$dn = "DC=FLRC,DC=local";
$group = "CN=Internet-Purchasing-Allowed,OU=Security Groups,DC=FLRC,DC=LOCAL";
$filter = "(&(objectClass=user)(memberOf=$group))";
$ad = ldap_connect("srv-flc-dc03") or die("Couldn't connect to AD!");
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ad, LDAP_OPT_REFERRALS,0);
$bd = ldap_bind( $ad, $valid_session_username."#flrc.local", $valid_session_password) or die("Can't bind to server.");
$sr = ldap_search($ad, $dn, $filter);
$found = false;
if ($sr !== false) {
$count = ldap_count_entries ($ad, $sr);
if ($count !== false && $count > 0) {
$found = true;
}
}
if ($found === true) {
print $valid_session_username.' does have access to this page';
} else {
print $valid_session_username.' does NOT have access to this page';
}
?>
I have no idea what I'm missing. When I submit my credentials it says "SRAY does have access to this page". Which is what it is suppose to say since SRAY is part of that group. It also says this for another username/pass that is NOT part of that security group.
Your filter is looking for any user that is a direct member of the Internet-Purchasing-Allowed group. You need to add (sAMAccountName=$valid_session_username) to your filter.
You must define sAMAccountname in your filter
//MEMBER OF THIS GROUP
$dn = "DC=FLRC,DC=local";
$group = "CN=Internet-Purchasing-Allowed,OU=Security Groups,DC=FLRC,DC=LOCAL";
$filter = "(&(objectClass=user)(sAMAccountname=".$valid_session_username.")(memberOf=".$group."))";
You must bind the LDAP with an account that has the necessary rights. Create an administrator account that has read permissions on all the "OU=Security Groups". Then bind with it in your code.
$bd = ldap_bind( $ad, $admin_session_username."#flrc.local", $admin_session_password) or die("Can't bind to server.");

Search Multiple AD DN's withPHP

Hi I have a PHP script that searches my AD, but how can I make it search more than one DN. I've tried the exmample on php.net and cannot get it to work.
Help appreciated:
<?php echo "<?xml version='1.0' encoding='utf-8' ?>" ?><?php echo "<ul class='LSRes'>" ?>
<?php
if( isset($_GET['q']) &&!empty($_GET['q']) ){
// all your ldap code
// Designate a few variables
$host = "10.10.10.10"; // Add in your AD host name or IP
$user = "DOMAIN\user"; // Add in your AD access account user name
$pswd = "password"; // Add in your AD access account user name password
$ds = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ds, $user, $pswd)
or die ("Could not bind");
// Create the DN - Add in the OU of your AD
$dn[] = "OU=uk,OU=Accounts,DC=mywebsite,DC=com";
$dn[] = "OU=us,OU=Accounts,DC=mywebsite,DC=com";
$id[] = $ds;
$id[] = $ds;
//$filter = 'samaccountname='.$_POST['username'];
$filter = "(|(givenName=".$_GET['q']."*) (sn=".$_GET['q']."*) (displayname=".$_GET['q']."*) (samaccountname=".$_GET['q']."*))";
$result = ldap_search($id,$dn,$filter);
$search = false;
foreach ($result as $value) {
if(ldap_count_entries($ds,$value)>0){
$search = $value;
break;
}
}
if($search){
$entries = ldap_get_entries($ds, $search);
}
if ($entries["count"] > 0) {
for ($i=0; $i<$entries["count"]; $i++) {
echo "<span class='LSstyle'>Name: <strong>".$entries[$i]["displayname"][0]." ".$entries[$i]["sn"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Short name: <strong>".$entries[$i]["samaccountname"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Phone: <strong>".$entries[$i]["telephonenumber"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Title: <strong>".$entries[$i]["title"][0]."</strong></span><br />";
echo "<span class='LSstyle'>Dept: <strong>".$entries[$i]["department"][0]."</strong></span></p>";
}
} else {
echo "<span class='LSstyle_noresults'><strong>No results found</strong></span>";
}
ldap_unbind($ad);
}
?>
Seeing as ldap_search does not take an array as $base_dn, you will probably have to loop $dn as Viper_Sb suggested.

Categories