Greetings. So today I'm gonna write about stuff. Managing basic LDAP things with PHP, to be precise... Had a problem at work, that sometimes we do not receive information about new people when they get accepted. Because we don't receive any information, we don't always know what to import/create. Then those people come to us asking why they can't log into computers and use Wifi, then we have to look them up in a outside Oracle DB and create a user like that. That's a silly, repetitive and a daunting task. Some kinda tool to automate this had to be created so it could be integrated into our existing IT system as well.
I'm not gonna write about the tool, instead I'll be writing about problems that came up adding users, creating groups and modifying attributes.
To begin with, I worked with Microsoft's ActiveDirectory on a local server. Tried to install LDAP plugins on localhost so I could develop it from my machine, but that went crashing down, it was relatively easy to install those LDAP plugins though. Anyhow, then I just coded on localhost and when I needed to run the stuff, I transferred that to an LDAP server. Was not cool at first, gotta transfer everything by hand, but then I remembered there is a plugin for Notepad++ called
NppFTP which automates that. Transfer everything with an FTP client, connect to that FTP through NppFTP and open documents straight from the FTP window and so the plugin uploads everything automatically on save.
That said, let's start with actual development.
PHP LDAP documentation is pretty much all you need for most of the things, but I had few problems with some of the functions. If you are working with MS's AD, then
this is also useful. Connecting is simple, but if you later need to create users and change passwords, you'll have to do that over SSL (port 636). Otherwise port 389 is enough.
Connecting and reading is pretty straight-forward once you know how LDAP distinguished names work. You have to get it just right, otherwise all you get is "Invalid Syntax" error without any additional details and there can be various shit wrong with your request...
When I was stuck I resorted to searching for helper projects that would ease my life interacting with LDAP and I found a decent one, called
adLDAP - but it was more help for me as a reference than framework and it was a great one.
I'm gonna give you some code snippets for reading first.
private function connect() {
$tinka = FALSE;
// go into a loop, because sometimes the connection breaks for no reason...
while ($tinka == FALSE) {
$ldap = ldap_connect($this->config['ldapServers'], 636) or die ("Error trying to connect: ".ldap_errno($ldap)." - ".ldap_error($ldap));
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
// echo "<br/>".$ldap; die();
$bind = ldap_bind($ldap, $this->config['ldapUsername'], $this->config['ldapPassword']);
// echo $bind; die();
// var_dump($bind); die();
if (($bind == 1) && $ldap) {
return $ldap;
} else {
return null;
}
}
}
To list login names, you can use this function:
public function getNames($fetchDisabled = true) {
$ldap = $this->connect();
$dn = 'OU=Folder, dc=subdomain, dc=domain, dc=com';
if ($fetchDisabled) { // count everyone
$results = ldap_search($ldap, $dn, '(objectClass=User)', array('samaccountname'));
} else { // omit disabled
$results = ldap_search($ldap, $dn, '(&(objectClass=User)(userAccountControl=512))', array('samaccountname'));
}
$data = ldap_get_entries($ldap, $results);
// echo "<pre>"; print_r($data); die();
$naujas = array();
foreach($data as $key => $reiksme) {
$entry = $reiksme['samaccountname'][0];
if (trim($entry) != "") {
$naujas[] = $entry;
}
}
return $naujas;
}
To check if a person exists by his login name:
public function exists($name) {
$ldap = $this->connect();
$dn = 'OU=Folder, dc=subdomain, dc=domain, dc=com';
$results = ldap_search($ldap, $dn, '(samaccountname='.$name.')', array('samaccountname'));
return ldap_count_entries($ldap, $results) > 0;
}
To get some summary of any person:
public function getPersonSummary($name) {
$ldap = $this->connect();
$dn = 'OU=Folder, dc=subdomain, dc=domain, dc=com';
$results = ldap_search($ldap, $dn, '(samaccountname='.$name.')', array('samaccountname', 'displayName', 'memberof'));
$data = ldap_get_entries($ldap, $results);
// echo "<pre>"; print_r($data); die();
$summaryArr['login_name'] = $data[0]['samaccountname'][0];
$summaryArr['name'] = $data[0]['displayname'][0];
$a = explode(",", $data[0]['memberof'][0]);
$a = explode("=", $a[0]);
$summaryArr['group'] = $a[1];
return $summaryArr;
}
To disable a person, use this. The number can probably either be 546 or 2 for disabled people. I use 2 and it works for me, when I print out the array I get from LDAP with already disabled people, they have that value set as 546(?).
public function disablePerson($name) {
$dn = 'CN='.$name.', OU=Folder, DC=Subdomain, DC=domain ,DC=com';
$ldap = $this->connect();
$personInfo['userAccountControl'] = 2;
ldap_modify($ldap, $dn, $personInfo);
}
Checking if user is disabled:
private function isUserDisabled($ldap, $name) {
$dn = 'OU=Folder, dc=subdomain, dc=domain, dc=com';
$results = ldap_list($ldap, $dn, '(samaccountname='.$name.')', array('useraccountcontrol'));
$data = ldap_get_entries($ldap, $results);
return (($data[0]['useraccountcontrol'][0] == 546) || ($data[0]['useraccountcontrol'][0] == 2));
}
Deleting a group:
public function deleteGroup($groupName) {
$dn = 'CN='.$groupName.', OU=GroupFolder, DC=subdomain, DC=domain, DC=com';
$ldap = $this->connect();
$r = ldap_delete($ldap, $dn);
if (!$r) { // someshit failed man!
echo ldap_error($ldap); die();
}
}
Renaming a group uses a function that isn't well documented, however example code in the PHP LDAP docs submitted by other uses were helpful enough:
public function renameGroup($oldGroup, $newGroup) {
// echo "<pre>"; print_r($newGroup); die();
$ldap = $this->connect();
$dn = 'CN='.$oldGroup.', OU=GroupFolder, DC=subdomain, DC=domain, DC=com';
// first we replace the attributes of the group
$grupeArr['samaccountname'] = $newGroup;
$grupeArr['mail'] = $newGroup.'@ish.ish.com';
$grupeArr['description'] = $newGroup;
$r = ldap_modify($ldap, $dn, $grupeArr);
if (!$r) { // someshit failed man!
echo ldap_error($ldap); die();
}
// now we rename the group. Memberof in people profiles changes automatically
$newDn = 'CN='.$newGroup; // name of our new entry
$newParent = 'OU=GroupFolder, DC=subdomain, DC=domain, DC=com'; // full DN without the name entry
$r = ldap_rename($ldap, $dn, $newDn, $newParent, true); // yes, we want to remove the old entry when renaming
if (!$r) { // someshit failed man!
echo ldap_error($ldap); die();
}
}
Now about writing new entries in LDAP. Creating a group is pretty easy. Well, actually it all is pretty easy now that I have it figured out, but before I had it was a bit of a mindfuck creating new people. For groups I use this:
public function createGroup($groupName) {
$dn = 'CN='.$groupName.', OU=GroupFolder, DC=subdmain, DC=domain, DC=com';
$ldap = $this->connect();
$grupeArr['samaccountname'] = $groupName;
$grupeArr['mail'] = $groupName.'@ish.ish.com';
$grupeArr['description'] = $groupName;
$grupeArr['objectclass'] = array('top', 'group');
$r = ldap_add($ldap, $dn, $grupeArr);
if (!$r) { // someshit failed man!
echo ldap_error($ldap); die();
}
}
When creating a new entry, the "objectclass" attribute has to be specified in full. I suggest looking what values do groups have in the folder you are creating new group so you know what to put there. Otherwise LDAP won't accept your request. I think "top" is always the first and it goes in everywhere.
Creating a user you gotta get all the fields you use correctly. Character case doesn't matter and we don't use a lot of attributes. Debugging was painful but finally got it down
$personInfo['samaccountname'] = $row_savnr['ISKKG']; // pre-win2k user
$personInfo['userPrincipalName'] = $row_savnr['ISKKG'].'@subdomain.domain.com'; // user name for logging in
$personInfo['givenName'] = $vardPavard[1]; // name
$personInfo['sn'] = $vardPavard[0]; // lastname
$personInfo['displayName'] = $row_savnr['PAVAR']; // how the name will be displayed once this user logs in
$personInfo['description'] = $row_savnr['GRUPE']; // obviously a description...
$personInfo['homeDrive'] = 'H:'; // network drive mount point
$personInfo['homeDirectory'] = '\\\\servername\\userdata$\\'.$row_savnr['ISKKG'];
$personInfo['profilePath'] = '\\\\servername\\profiles$\\'.$row_savnr['ISKKG'];
$personInfo['scriptPath'] = 'rmrf.bat';
$personInfo['mail'] = $row_savnr['ISKKG'].'@subdomain.domain.com'; // work mail with username
$personInfo['wwwHomePage'] = strtolower($this->makePlain($vardPavard[1]).'.'.$this->makePlain($vardPavard[0]).'@subdomain.domain.com'); // also work mail with name.lastname, must be plaintext (not Unicode) though
$personInfo['objectclass'] = array('top', 'person', 'organizationalPerson', 'user'); // class of this object/user. Look this up from others already created if you can, if not then ask your angry sysadmin :P
$personInfo['unicodePwd'] = $this->encodePassword('supuhpasswdover9000'); // has to be specially encoded, I don't think you can use a Unicode passwd with this field, even though it is named UnicodePwd...
$personInfo['userAccountControl'] = 512; // normal account, without this bit set, our user will be created as locked out
$personInfo['pwdlastset'] = 0; // with this bit the user will have to change his passwd on next logon
$personInfo['telephoneNumber'] = $row_savnr['STELEF'];
And of course the password has to be encoded in a special/weird way, this is the function everyone uses:
private function encodePassword($password) {
$password="\"".$password."\"";
$encoded = "";
for ($i = 0; $i < strlen($password); $i++) {
$encoded .= "{$password{$i}}\000";
}
return $encoded;
}