Fedora Linux Support Community & Resources Center
  #1  
Old 11th March 2017, 05:19 AM
Jeff Sadowski Offline
Registered User
 
Join Date: Jun 2005
Age: 42
Posts: 465
linuxchrome
How to change AD password with php

Code:
<?php
if((!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on") && isset($_SERVER["HTTP_HOST"]))
{header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
  exit();
}
/**
 * Created by Jeff Sadowski with much help from a bunch of other scripts found through out the internet.
 */
function command_exist($cmd){$returnVal = shell_exec(sprintf("which %s", escapeshellarg($cmd)));return !empty($returnVal);}
$needed_exists=true;

if(!defined('DNS_SRV')){define('DNS_SRV','SRV');}

function my_dns_get_record($host,$type='ANY')
{global $global_ad;
 $output=array();
 if(defined('DNS_SRV') && $type==DNS_SRV){$type="SRV";}
 $cmd="nslookup -type=".$type." ".$host." ".$global_ad;
 foreach(explode("\n",explode("\n\n",shell_exec($cmd))[1]) as $entry)
 {$part=array();
  $temp=explode("\t",$entry);
  $part["host"]=$temp[0];
  $temp=explode(" ",explode("= ",$temp[1])[1]);
  $part["pri"]=$temp[0];
  $part["weight"]=$temp[1];
  $part["port"]=$temp[2];
  $part["target"]=$temp[3];
  array_push($output,$part);
 }
 return $output;
}

if(!function_exists("ldap_connect"))
{echo "You will need function ldap_connect this php script is pointless without it.\n";
 $needed_exists=false;
}
if(!command_exist("nslookup"))
{echo "You will need the shell command nslookup so this php script can get the domain search lists.\n";
 $needed_exists=false;
}

if(!$needed_exists){exit();}

function adifyPw($pw){return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"');}

$domains=explode("/",preg_replace("/.*srchlist =\s*([^;]*).*/","$1",str_replace("\n",";",shell_exec("echo set all|nslookup"))));

$pdcs=array();
$good_domains=array();
foreach($domains as $ad)
{$global_ad=$ad;
// $pdcs[$ad]=dns_get_record("_ldap._tcp.pdc._msdcs.".$ad,DNS_SRV);
 $pdcs[$ad]=my_dns_get_record("_ldap._tcp.pdc._msdcs.".$ad,DNS_SRV);
 if(!(isset($pdcs[$ad]) && isset($pdcs[$ad][0]) && isset($pdcs[$ad][0]["target"]) && isset($pdcs[$ad][0]["port"])))
 {echo "Check your domain's DNS.<br>\n";
  echo "All domain controllers should also be DNS servers.<br>\n";
  echo "They should have an entry for _ldap._tcp.pdc._msdcs.<br>".$ad."\n";
  echo "Make sure this server is pointing to the domain controllers for it's DNS.<br>\n";
 }
 else
 {array_push($good_domains,$ad);
}}
$domains=$good_domains;

define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032);
if(isset($_REQUEST['username']) && isset($_REQUEST['password']) && isset($_REQUEST['newpass']) && isset($_REQUEST['domain']))
{putenv('LDAPTLS_REQCERT=never');
 ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
 $ldap_string='ldap://'.$pdcs[$_REQUEST['domain']][0]["target"].':'.$pdcs[$_REQUEST['domain']][0]["port"];
 $ldap = ldap_connect($ldap_string) or 
         die('Could not connect to LDAP server '.$ldap_string.'.');

 $ldaprdn = strtoupper(explode('.',$_REQUEST['domain'])[0]) . "\\" . $_POST['username'];
 echo "username:".$ldaprdn."<br>\n";

 ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Could not set version 3.");
 ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0) or die("Could not set refrerals to 0");
 ldap_start_tls($ldap);
 $bind = @ldap_bind($ldap, $ldaprdn, $_POST['password']);

 if($bind)
 {$result = ldap_search($ldap,'dc='.str_replace('.',',dc=',strtoupper($_REQUEST['domain'])),'(sAMAccountName='.$_POST['username'].')');
  ldap_sort($ldap,$result,"sn");
  $info = ldap_get_entries($ldap, $result);
  for($i=0; $i<$info["count"]; $i++)
  {if($info['count'] > 1){break;}
   $userDn = $info[$i]["distinguishedname"][0];
   $modifs = [[ "attrib"  => "unicodePwd", "modtype" => LDAP_MODIFY_BATCH_REMOVE, "values"  => [adifyPw($_POST['password'])], ],
              [ "attrib"  => "unicodePwd", "modtype" => LDAP_MODIFY_BATCH_ADD,    "values"  => [adifyPw($_POST['newpass']) ], ], ];

   if(ldap_modify_batch($ldap, $userDn, $modifs))
   { print "You have successfully changed your password.";
   }
   else
   {if(ldap_errno($ldap)==53)
    {echo $ldap_string." is not actting like the PDC I must have gotten a bad record from DNS";
    }
    elseif(ldap_errno($ldap)==19)
    {echo "Password must be 8 or more characters. <br>";
     echo "Password must contain 3 of the four types described: <ul><li>Uppercase letters</li>";
     echo "<li>Lowercase letters</li><li>Number characters</li><li>Special characters ex:[!@#$%^&*()-+]</li></ul>";
     echo "Password must not have been used before";
    }
    else
    {echo "failed:[". ldap_errno($ldap)."] [". ldap_error($ldap). "]";
  }}}
  @ldap_close($ldap);
 }
 else
 {if(ldap_get_option($ldap, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error))
  {$errno = intval(preg_replace("/.*,\s*data\s*([^,]*),.*/i","$1",$extended_error));
   if($errno == 52){echo "Unable to login: Invalid user, you typed your password wrong or you don't know your current password.";}
   elseif($errno == 532){echo "Unable to login: Password expired.";}
   elseif($errno == 533){echo "Unable to login: Your account has been dissabled (Maybe you didn't do your HIPPA).";}
   elseif($errno == 701){echo "Unable to login: Your account has expired ask IT to give your account another 6 months.";}
   else
   {echo "Error [".$errno."] Binding to LDAP: " . $extended_error;
    echo " Please let IT know this exact message as it will aid other users from this unexpected message.";
  }}
  else
  {echo "Error Binding to LDAP: No additional information is available. Most likely I could not contact ". $ldap_string ."\n";
}}}
else
{
?>
<script>
function checkPassword(theForm)
{var Lowercase=false;
 var Uppercase=false;
 var Number=false;
 var SpecialCharacter=false;
 var three_of_four=0;
 var error=false;

 if(theForm.newpass.value != theForm.cnewpass.value )
 {alert('"Confirm New Password" must match "New Password"');
  error=true;
 }
 var re = /[0-9]/;
 if(re.test(theForm.newpass.value)) { Number=true; three_of_four++;}
 re = /[a-z]/;
 if(re.test(theForm.newpass.value)) { Lowercase=true; three_of_four++;}
 re = /[A-Z]/;
 if(re.test(theForm.newpass.value)) { Uppercase=true; three_of_four++;}
 re = /[^A-Za-z0-9]/;
 if(re.test(theForm.newpass.value)) { SpecialCharacter=true; three_of_four++;}
 if(three_of_four<3)
 {alert("Self set password must contain 3 of the four types described:"+
        " \n\t•Uppercase letters\n\t•Lowercase letters\n\t•Number characters\n\t•Special characters ex:[!@#$%^&*()-+]");
  error=true;
 }
 if(theForm.newpass.value.length < 8)
 {alert("Self set password must be 8 or more characters long.");
  error=true;
 }
 if(theForm.password.value == "")
 {alert('Password can not be blank. If it really is blank you will need IT to change it. This page can not use a blank password.');
  error=true;
 }
 if(error){return false;}
 return true;
}
</script>
<form action="#" method="POST" onsubmit="return checkPassword(this)">
<table><tr><td align="right">Domain: </td><td>
<select name="domain">
<?php 
foreach($domains as $ad)
{$selected="";
 if(isset($_REQUEST["domain"]) && $ad==$_REQUEST["domain"]){$selected=" selected=\"selected\"";}
 echo "<option value=".$ad.$selected.">".$ad."</option>";
}
?>
</select></td><tr>
<tr><td align="right"><label for="username">Username: </label></td><td><input id="username" type="text" name="username" value="<?php 
if(isset($_REQUEST['username'])){echo $_REQUEST['username'];} ?>"/></td></tr>
<tr><td align="right"><label for="password">Password: </label></td><td><input id="password" type="password" name="password" /></td></tr>
<tr><td align="right"><label for="newpass">New Password: </label></td><td><input id="newpass" type="password" name="newpass" /></td></tr>
<tr><td align="right"><label for="cnewpass">Confirm New Password: </label></td><td><input id="cnewpass" type="password" name="cnewpass"/></td></tr>
<tr><td align="right"></td><td><input type="submit" name="submit" value="Submit" /></td></tr>
</table>
</form>
<?php } ?>

Last edited by Jeff Sadowski; 13th March 2017 at 06:29 PM.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Fedora 24 not saving WiFi password after user account password change. noviceFedora Servers & Networking 2 18th September 2016 05:58 AM
Log in, BUT can't change password SA Penguin Using Fedora 6 4th January 2011 09:50 PM
can't change password? bigmacbb63 Security and Privacy 4 15th November 2006 08:44 PM
can't change password asoduk Using Fedora 2 6th July 2005 10:55 PM


Current GMT-time: 20:21 (Thursday, 30-03-2017)

TopSubscribe to XML RSS for all Threads in all ForumsFedoraForumDotOrg Archive
logo

All trademarks, and forum posts in this site are property of their respective owner(s).
FedoraForum.org is privately owned and is not directly sponsored by the Fedora Project or Red Hat, Inc.

Privacy Policy | Term of Use | Posting Guidelines | Archive | Contact Us | Founding Members

Powered by vBulletin® Copyright ©2000 - 2012, vBulletin Solutions, Inc.

FedoraForum is Powered by RedHat