public static function checkLdapCredentials($username, $password)
 {
     $options = sfConfig::get('app_sf_guard_plugin_ldap_settings', array());
     $ldap = new adLDAP($options);
     $authenticated = $ldap->authenticate($username, $password);
     return $authenticated ? true : false;
 }
Esempio n. 2
0
 public function executeSignin($request)
 {
     $this->form = new sfGuardFormSignin();
     if ($request->isMethod('post')) {
         $data = $request->getParameter('signin');
         $adldap = new adLDAP(array('account_suffix' => '@sch.bme.hu', 'domain_controllers' => array('152.66.208.42'), 'ad_username' => $data['username'], 'ad_password' => $data['password']));
         try {
             $authUser = $adldap->authenticate($data['username'], $data['password']);
             if ($authUser === true) {
                 $userData = $adldap->user_info($data['username']);
                 $user = Doctrine::getTable('sfGuardUser')->findOneBy('username', $data['username']);
                 $save = false;
                 if ($user) {
                     if ($user->Profile->full_name != $userData[0]["displayname"][0] || $user->Profile->email != $userData[0]["mail"][0]) {
                         $save = true;
                     }
                 } else {
                     $user = new sfGuardUser();
                     $save = true;
                 }
                 if ($save) {
                     $user->username = $data['username'];
                     $user->password = $data['password'];
                     $user->Profile->full_name = $userData[0]["displayname"][0];
                     $user->Profile->email = $userData[0]["mail"][0];
                     $user->save();
                 }
             }
         } catch (Exception $e) {
             echo $e;
         }
     }
     parent::executeSignin($request);
 }
Esempio n. 3
0
function GetDomainUsersList()
{
    global $SAMSConf;
    global $USERConf;
    if ($USERConf->ToWebInterfaceAccess("UC") != 1) {
        exit;
    }
    $DB = new SAMSDB();
    if ($SAMSConf->AUTH == "ntlm") {
        $value = ExecuteShellScript("getwbinfousers", "{$SAMSConf->WBINFOPATH}/");
        $a = explode(" ", $value);
        sort($a);
        $acount = count($a);
    } else {
        require_once "adldap.php";
        //create the LDAP connection
        $pdc = array("{$SAMSConf->LDAPSERVER}");
        $options = array(account_suffix => "@{$SAMSConf->LDAPDOMAIN}", base_dn => "{$SAMSConf->LDAPBASEDN}", domain_controllers => $pdc, ad_username => "{$SAMSConf->LDAPUSER}", ad_password => "{$SAMSConf->LDAPUSERPASSWD}", "", "", "");
        $ldap = new adLDAP($options);
        $a = $ldap->all_users($include_desc = false, $search = "*", $sorted = true);
        sort($a);
        $acount = count($a);
    }
    print "<SELECT NAME=\"usernick\" ID=\"usernick\" SIZE=1 >\n";
    for ($i = 0; $i < $acount; $i++) {
        if ($SAMSConf->NTLMDOMAIN == "Y") {
            if (strstr($a[$i], "+") != NULL) {
                $domain = trim(strtok($a[$i], "+"));
                $user = trim(strtok("+"));
                $domainlen = strlen($domain);
                $userlen = strlen($user);
            } else {
                $domain = trim(strtok($a[$i], "\\"));
                $user = trim(strtok("\\"));
                $domainlen = strlen($domain);
                $userlen = strlen($user);
            }
            if (strlen($domain) == 0 || strlen($user) == 0) {
                $user = $domain;
                $domain = $SAMSConf->DEFAULTDOMAIN;
            }
        } else {
            $domain = "{$SAMSConf->DEFAULTDOMAIN}";
            $user = trim($a[$i]);
            //$user=strtolower($user);
        }
        $result = $DB->samsdb_query("SELECT * FROM squidusers WHERE domain=\"{$domain}\"&&nick=\"{$user}\" ");
        $row = $DB->samsdb_fetch_array($result);
        if (strcmp($row['name'], $user) != 0 && strcmp($row['domain'], $domain) != 0) {
            if ($SAMSConf->NTLMDOMAIN == "Y") {
                print "<OPTION VALUE=\"{$domain}+{$user}\"> {$user}/{$domain} ";
            } else {
                print "<OPTION VALUE=\"{$user}\"> {$user} ";
            }
        }
    }
    print "</SELECT>\n";
}
Esempio n. 4
0
function ADLDtest()
{
    global $SAMSConf;
    global $USERConf;
    if ($USERConf->ToWebInterfaceAccess("C") != 1) {
        exit;
    }
    $info = array();
    $lang = "./lang/lang.{$SAMSConf->LANG}";
    require $lang;
    print "<H1>Test AD connection</H1>";
    require_once "src/adldap.php";
    //create the LDAP connection
    $adldserver = GetAuthParameter("adld", "adldserver");
    $basedn = GetAuthParameter("adld", "basedn");
    $adadmin = GetAuthParameter("adld", "adadmin");
    $adadminpasswd = GetAuthParameter("adld", "adadminpasswd");
    $usergroup = GetAuthParameter("adld", "usergroup");
    $LDAPBASEDN2 = strtok($basedn, ".");
    $LDAPBASEDN = "DC={$LDAPBASEDN2}";
    while (strlen($LDAPBASEDN2) > 0) {
        $LDAPBASEDN2 = strtok(".");
        if (strlen($LDAPBASEDN2) > 0) {
            $LDAPBASEDN = "{$LDAPBASEDN},DC={$LDAPBASEDN2}";
        }
    }
    $pdc = array("{$adldserver}");
    $options = array(account_suffix => "@{$basedn}", base_dn => "{$LDAPBASEDN}", domain_controllers => $pdc, ad_username => "{$adadmin}", ad_password => "{$adadminpasswd}", "", "", "");
    $ldap = new adLDAP($options);
    $charset = explode(",", $_SERVER['HTTP_ACCEPT_CHARSET']);
    $groups = $ldap->all_groups($include_desc = false, $search = "*", $sorted = true);
    $gcount = count($groups);
    print "<TABLE CLASS=samstable>";
    print "<TH width=5%>No";
    print "<TH >{$adldtest_1_authldaptray} {$basedn}";
    for ($i = 0, $j = 1; $i < $gcount; $i++, $j++) {
        $groupname = UTF8ToSAMSLang($groups[$i]);
        echo "<TR><TD>{$j}:<TD>{$groupname} <BR>";
    }
    echo "</TABLE><P>";
    $users = $ldap->all_users($include_desc = false, $search = "*", $sorted = true);
    $count = count($users);
    print "<TABLE CLASS=samstable>";
    print "<TH width=5%>No";
    print "<TH >{$adldtest_2_authldaptray} {$basedn}";
    print "<TH > ";
    $i = 0;
    foreach ($users as $user) {
        $i++;
        $samaccountname = UTF8ToSAMSLang($user["samaccountname"]);
        $displayname = UTF8ToSAMSLang($user["displayname"]);
        echo "<TR><TD>{$i}: <TD> {$samaccountname} <TD> {$displayname}";
    }
    echo "</TABLE>";
}
Esempio n. 5
0
 public function authAD()
 {
     $adldap = new adLDAP();
     if ($adldap->authenticate($this->login, $this->password)) {
         $user_info = $adldap->user()->info($this->login);
         $this->display_name = $user_info[0]['displayname'][0];
         $this->logged = true;
         $this->is_admin = $this->isAdmin($user_info);
     } else {
         $this->logged = false;
     }
 }
Esempio n. 6
0
function TestPDC()
{
    global $SAMSConf;
    $info = array();
    $lang = "./lang/lang.{$SAMSConf->LANG}";
    require $lang;
    if (isset($_GET["auth"])) {
        $auth = $_GET["auth"];
    }
    print "<H1>TEST PDC</H1>";
    $value = ExecuteShellScript("getwbinfousers", "{$SAMSConf->WBINFOPATH}");
    $a = explode(" ", $value);
    sort($a);
    $acount = count($a);
    if ($auth == "ntlm") {
        for ($i = 0; $i < $acount; $i++) {
            print "{$a[$i]}<BR>\n";
        }
    }
    if ($auth == "adld") {
        require_once "adldap.php";
        //create the LDAP connection
        $pdc = array("{$SAMSConf->LDAPSERVER}");
        $options = array(account_suffix => "@{$SAMSConf->LDAPDOMAIN}", base_dn => "{$SAMSConf->LDAPBASEDN}", domain_controllers => $pdc, ad_username => "{$SAMSConf->LDAPUSER}", ad_password => "{$SAMSConf->LDAPUSERPASSWD}", "", "", "");
        $ldap = new adLDAP($options);
        $groups = $ldap->all_groups($include_desc = false, $search = "*", $sorted = true);
        $gcount = count($groups);
        print "<TABLE CLASS=samstable>";
        print "<TH width=5%>No";
        print "<TH >{$SAMSConf->LDAPDOMAIN} groups";
        for ($i = 0; $i < $gcount; $i++) {
            echo "<TR><TD>{$i}:<TD>{$groups[$i]}<BR>";
        }
        echo "</TABLE><P>";
        $users = $ldap->all_users($include_desc = false, $search = "*", $sorted = true);
        $count = count($users);
        print "<TABLE CLASS=samstable>";
        print "<TH width=5%>No";
        print "<TH >{$SAMSConf->LDAPDOMAIN} users";
        for ($i = 0; $i < $count; $i++) {
            $userinfo = $ldap->user_info($users[$i], $fields = NULL);
            //$mcount=count($userinfo);
            echo "<TR><TD>{$i}:<TD> {$users[$i]} ";
            $aaa = $userinfo[0]["displayname"][0];
            //$aaa2 = $userinfo[0]["givenname"][0];
            //$aaa3 = $userinfo[0]["sn"][0];
            echo "<TD>{$aaa} ";
        }
        echo "</TABLE>";
    }
}
Esempio n. 7
0
 /**
  * Move a user account to a different OU
  *
  * @param string $username The username to move (please be careful here!)
  * @param array $container The container or containers to move the user to (please be careful here!).
  * accepts containers in 1. parent 2. child order
  * @return array
  */
 public function move($username, $container)
 {
     if (!$this->adldap->getLdapBind()) {
         return false;
     }
     if ($username === null) {
         return "Missing compulsory field [username]";
     }
     if ($container === null) {
         return "Missing compulsory field [container]";
     }
     if (!is_array($container)) {
         return "Container must be an array";
     }
     $userInfo = $this->info($username, array("*"));
     $dn = $userInfo[0]['distinguishedname'][0];
     $newRDn = "cn=" . $username;
     $container = array_reverse($container);
     $newContainer = "ou=" . implode(",ou=", $container);
     $newBaseDn = strtolower($newContainer) . "," . $this->adldap->getBaseDn();
     $result = @ldap_rename($this->adldap->getLdapConnection(), $dn, $newRDn, $newBaseDn, true);
     if ($result !== true) {
         return false;
     }
     return true;
 }
 function loginUser()
 {
     $ldapOptions = array('account_suffix' => '@solitude.guc.usg.edu', 'base_dn' => 'ou=GGCNet,dc=solitude,dc=guc,dc=usg,dc=edu', 'domain_controllers' => array('llyr.solitude.guc.usg.edu'));
     $ldapOptions = array('account_suffix' => '@ggc.edu', 'base_dn' => 'ou=GGCNet,dc=ggc,dc=edu', 'domain_controllers' => array('ldap.ggc.edu'));
     $ldap = new adLDAP($ldapOptions);
     if ($ldap->authenticate($_POST['login_user'], self::decryptRSA($_POST['login_pass']))) {
         $_SESSION['loggedInParking'] = strtolower($_POST['login_user']);
         // allow commenting
         $_SESSION['allowComments'] = true;
     } else {
         //print_r($_POST);
         //die("Invalid password / username combination.");
         header("location: index.php?error=1");
         die;
     }
 }
Esempio n. 9
0
 /**
  * Create an organizational unit
  *
  * @param array $attributes Default attributes of the ou
  * @return bool
  */
 public function create($attributes)
 {
     if (!is_array($attributes)) {
         return "Attributes must be an array";
     }
     if (!is_array($attributes["container"])) {
         return "Container attribute must be an array.";
     }
     if (!array_key_exists("ou_name", $attributes)) {
         return "Missing compulsory field [ou_name]";
     }
     if (!array_key_exists("container", $attributes)) {
         return "Missing compulsory field [container]";
     }
     $attributes["container"] = array_reverse($attributes["container"]);
     $add = array();
     $add["objectClass"] = "organizationalUnit";
     $add["OU"] = $attributes['ou_name'];
     $containers = "";
     if (count($attributes['container']) > 0) {
         $containers = "OU=" . implode(",OU=", $attributes["container"]) . ",";
     }
     $containers = "OU=" . implode(",OU=", $attributes["container"]);
     $result = ldap_add($this->adldap->getLdapConnection(), "OU=" . $add["OU"] . ", " . $containers . $this->adldap->getBaseDn(), $add);
     if ($result != true) {
         return false;
     }
     return true;
 }
Esempio n. 10
0
 function selectUserFromLdap($username, $password)
 {
     try {
         $adldap = new adLDAP();
         $adldap->set_account_suffix('@vejleidraetsefterskole.local');
         $adldap->set_domain_controllers(array('mail.vih.dk'));
     } catch (adLDAPException $e) {
         echo $e;
         exit;
     }
     $authUser = $adldap->authenticate($username, $password);
     if ($authUser === true) {
         return new k_AuthenticatedUser($username);
     } else {
         throw new Exception('User authentication unsuccessful. ' . $adldap->get_last_error());
     }
 }
 /**
  * Supprime un ordinateur de l'ad
  * @param type $computername
  * @param type $isGUID
  * @return boolean
  */
 public function delete($computername, $isGUID = false)
 {
     $userinfo = $this->info($computername, array("*"), $isGUID);
     $dn = $userinfo[0]['distinguishedname'][0];
     $result = $this->adldap->folder()->delete($dn);
     if ($result != true) {
         return false;
     }
     return true;
 }
Esempio n. 12
0
 /**
  *
  * @param string $username
  * @param string $password
  * @param string $method
  * @return Users 
  */
 public function getCredentials($username, $password, $method = 'internal')
 {
     if ($method == "ldap") {
         require_once ROOT_PATH . 'lib/common/ldap/adLDAP.php';
         $ldap = new adLDAP();
         // Authenticate using adLDAP configuratoin
         $authLdap = $ldap->authenticate($username, $password);
         if ($authLdap) {
             // Get the internally created user account (ESS/Admin accounts listed under users)
             $query = Doctrine_Query::create()->from('SystemUser')->where('user_name = ?', $username)->andWhere('deleted = 0');
         } else {
             // Return an empty result set if authentication is false
             $query = Doctrine_Query::create()->from('SystemUser')->where('1 = 2');
         }
     } else {
         $query = Doctrine_Query::create()->from('SystemUser')->where('user_name = ?', $username)->andWhere('user_password = ?', $password)->andWhere('deleted = 0');
     }
     return $query->fetchOne();
 }
 /**
  * !!!! Méthode ajouter !!!!
  * Active un ordinateur
  * 
  * @param string $dn le dn de l'ordinateur
  * @return bool
  */
 public function activerComputer($dn)
 {
     $controlOptions = array("PASSWD_NOTREQD", "WORKSTATION_TRUST_ACCOUNT");
     $mod["userAccountControl"][0] = $this->accountControl($controlOptions);
     $result = @ldap_modify($this->adldap->getLdapConnection(), $dn, $mod);
     if ($result == false) {
         return false;
     }
     return true;
 }
Esempio n. 14
0
 /**
  * Get the last logon time of any user as a Unix timestamp
  * 
  * @param string $username
  * @return long $unixTimestamp
  */
 public function getLastLogon($username)
 {
     if (!$this->adldap->getLdapBind()) {
         return false;
     }
     if ($username === null) {
         return "Missing compulsory field [username]";
     }
     $userInfo = $this->info($username, array("lastLogonTimestamp"));
     $lastLogon = adLDAPUtils::convertWindowsTimeToUnixTime($userInfo[0]['lastLogonTimestamp'][0]);
     return $lastLogon;
 }
Esempio n. 15
0
 /**
  * Returns a list of Databases within any given storage group in Exchange for a given mail server
  * 
  * @param string $storageGroup The full DN of an Storage Group.  You can use exchange_storage_groups() to find the DN 
  * @param array $attributes An array of the AD attributes you wish to return
  * @return array
  */
 public function storageDatabases($storageGroup, $attributes = array('cn', 'distinguishedname', 'displayname'))
 {
     if (!$this->adldap->getLdapBind()) {
         return false;
     }
     if ($storageGroup === NULL) {
         return "Missing compulsory field [storageGroup]";
     }
     $filter = '(&(objectCategory=msExchPrivateMDB))';
     $sr = @ldap_search($this->adldap->getLdapConnection(), $storageGroup, $filter, $attributes);
     $entries = @ldap_get_entries($this->adldap->getLdapConnection(), $sr);
     return $entries;
 }
Esempio n. 16
0
 function login($username, $password)
 {
     if ($password == 'vih') {
         $this->logged_in = true;
         return true;
     }
     if ($username != NULL && $password != NULL) {
         //include the class and create a connection
         require_once dirname(__FILE__) . '/adLdap.php';
         try {
             $adldap = new adLDAP();
         } catch (adLDAPException $e) {
             echo $e;
             exit;
         }
         //authenticate the user
         if ($adldap->authenticate($username, $password)) {
             $this->logged_in = true;
             return true;
         }
     }
     return false;
 }
Esempio n. 17
0
 /**
  * Coping with AD not returning the primary group
  * http://support.microsoft.com/?kbid=321360 
  * 
  * For some reason it's not possible to search on primarygrouptoken=XXX
  * If someone can show otherwise, I'd like to know about it :)
  * this way is resource intensive and generally a pain in the @#%^
  * 
  * @deprecated deprecated since version 3.1, see get get_primary_group
  * @param string $gid Group ID
  * @return string
  */
 public function cn($gid)
 {
     if ($gid === NULL) {
         return false;
     }
     $r = false;
     $filter = "(&(objectCategory=group)(samaccounttype=" . adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP . "))";
     $fields = array("primarygrouptoken", "samaccountname", "distinguishedname");
     $sr = ldap_search($this->adldap->getLdapConnection(), $this->adldap->getBaseDn(), $filter, $fields);
     $entries = ldap_get_entries($this->adldap->getLdapConnection(), $sr);
     for ($i = 0; $i < $entries["count"]; $i++) {
         if ($entries[$i]["primarygrouptoken"][0] == $gid) {
             $r = $entries[$i]["distinguishedname"][0];
             $i = $entries["count"];
         }
     }
     return $r;
 }
Esempio n. 18
0
 /**
  * Get the groups a computer is in
  * 
  * @param string $computerName The name of the computer
  * @param bool $recursive Whether to check recursively
  * @return array
  */
 public function groups($computerName, $recursive = NULL)
 {
     if ($computerName === NULL) {
         return false;
     }
     if ($recursive === NULL) {
         $recursive = $this->adldap->getRecursiveGroups();
     }
     //use the default option if they haven't set it
     if (!$this->adldap->getLdapBind()) {
         return false;
     }
     //search the directory for their information
     $info = @$this->info($computerName, array("memberof", "primarygroupid"));
     $groups = $this->adldap->utilities()->niceNames($info[0]["memberof"]);
     //presuming the entry returned is our guy (unique usernames)
     if ($recursive === true) {
         foreach ($groups as $id => $groupName) {
             $extraGroups = $this->adldap->group()->recursiveGroups($groupName);
             $groups = array_merge($groups, $extraGroups);
         }
     }
     return $groups;
 }
 /**
  * __construct
  *
  * fixes all the of options for passing up to the parent constructer
  *
  * @param array $options
  */
 function __construct($options = array())
 {
     $conf = PSUDatabase::connect('ldap/password', 'return');
     $conf['password'] = PSUSecurity::password_decode($conf['password']);
     if (empty($options)) {
         $options['account_suffix'] = "@plymouth.edu";
         $options['base_dn'] = $conf['dn'];
         $options['domain_controllers'] = array($conf['hostname'], $conf['hostname2']);
         $options['ad_username'] = $conf['username'];
         $options['ad_password'] = $conf['password'];
         $options['real_primarygroup'] = true;
         $options['use_ssl'] = true;
         $options['recursive_groups'] = true;
     }
     parent::__construct($options);
 }
Esempio n. 20
0
function checkcreds_ADGroups_ToServer($groups, $hostname, $username, $password, $account_suffix)
{
    if (strlen($groups) == 0) {
        if ($GLOBALS["HOTSPOT_DEBUG"]) {
            ToSyslog("{$hostname}: checkcreds_ADGroups_ToServer no defined group in line:" . __LINE__);
        }
        return true;
    }
    $YGroups = array();
    $zGroups = explode("\n", $groups);
    while (list($num, $ligne) = each($zGroups)) {
        $ligne = trim(strtolower($ligne));
        if ($ligne == null) {
            continue;
        }
        $YGroups[$ligne] = $ligne;
        if ($GLOBALS["HOTSPOT_DEBUG"]) {
            ToSyslog("{$hostname}: checkcreds_ADGroups_ToServer checks group {$ligne} in line:" . __LINE__);
        }
    }
    if ($GLOBALS["HOTSPOT_DEBUG"]) {
        ToSyslog("{$hostname}: checkcreds_ADGroups_ToServer " . count($YGroups) . " in line:" . __LINE__);
    }
    if (count($YGroups) == 0) {
        if ($GLOBALS["HOTSPOT_DEBUG"]) {
            ToSyslog("{$hostname}: checkcreds_ADGroups_ToServer no group defined, return true in line:" . __LINE__);
        }
        return true;
    }
    if ($GLOBALS["HOTSPOT_DEBUG"]) {
        ToSyslog("{$hostname}: checkcreds_ADGroups_ToServer checks {$username} groups in line:" . __LINE__);
    }
    $account_suffixZ = explode(".", $account_suffix);
    while (list($num, $a) = each($account_suffixZ)) {
        $zsuffix[] = "DC={$a}";
    }
    $suffix = @implode(",", $zsuffix);
    $options = array('base_dn' => $suffix, 'ad_username' => $username, 'ad_password' => $password, 'recursive_groups' => true, 'domain_controllers' => array($hostname), 'account_suffix' => "@{$account_suffix}");
    $adldap = new adLDAP($options);
    $adldap->authenticate("{$username}", $password);
    $result = $adldap->user()->groups($username);
    if ($GLOBALS["HOTSPOT_DEBUG"]) {
        ToSyslog_array($GLOBALS["CLASS_ACTV"]);
    }
    if ($GLOBALS["HOTSPOT_DEBUG"]) {
        ToSyslog("{$hostname}: checkcreds_ADGroups_ToServer {$username} in:" . count($result) . " groups in line:" . __LINE__);
    }
    while (list($num, $group) = each($result)) {
        $group = trim(strtolower($group));
        if ($GLOBALS["HOTSPOT_DEBUG"]) {
            ToSyslog("{$hostname}: checkcreds_AD checks {$group} group in line:" . __LINE__);
        }
        if (isset($YGroups[$group])) {
            if ($GLOBALS["HOTSPOT_DEBUG"]) {
                ToSyslog("{$hostname}: checkcreds_AD checks {$group} is OK in line:" . __LINE__);
            }
            return true;
        }
    }
    return false;
}
if (strlen(@$params->adminUsername) == 0 || strlen(@$params->adminPassword) == 0) {
    $Result->show("danger", _("Missing credentials"), true);
}
//at least 2 chars
if (strlen($_POST['dfilter']) < 2) {
    $Result->show("danger", _('Please enter at least 2 characters'), true);
}
//open connection
try {
    if ($server->type == "NetIQ") {
        $params->account_suffix = "";
    }
    //set options
    $options = array('base_dn' => $params->base_dn, 'account_suffix' => $params->account_suffix, 'domain_controllers' => explode(";", $params->domain_controllers), 'use_ssl' => $params->use_ssl, 'use_tls' => $params->use_tls, 'ad_port' => $params->ad_port);
    //AD
    $adldap = new adLDAP($options);
    //try to login with higher credentials for search
    $authUser = $adldap->authenticate($params->adminUsername, $params->adminPassword);
    if ($authUser == false) {
        $Result->show("danger", _("Invalid credentials"), true);
    }
    // set OpenLDAP flag
    if ($server->type == "LDAP") {
        $adldap->setUseOpenLDAP(true);
    }
    //search groups
    $groups = $adldap->group()->search(adLDAP::ADLDAP_SECURITY_GLOBAL_GROUP, true, "*{$_POST['dfilter']}*");
    //echo $adldap->getLastError();
} catch (adLDAPException $e) {
    $Result->show("danger", $adldap->getLastError(), false);
    $Result->show("danger", $e->getMessage(), true);
Esempio n. 22
0
 /**
  * Checks the config.php AUTHCFG value for login type and forks off to the proper module
  *
  * @param string $user_password - The password of the user to authenticate
  * @return true if the user is authenticated, false otherwise
  */
 function doLogin($user_password)
 {
     global $AUTHCFG;
     $usr_name = $this->column_fields["user_name"];
     switch (strtoupper($AUTHCFG['authType'])) {
         case 'LDAP':
             $this->log->debug("Using LDAP authentication");
             require_once 'modules/Users/authTypes/LDAP.php';
             $result = ldapAuthenticate($this->column_fields["user_name"], $user_password);
             if ($result == NULL) {
                 return false;
             } else {
                 return true;
             }
             break;
         case 'AD':
             $this->log->debug("Using Active Directory authentication");
             require_once 'modules/Users/authTypes/adLDAP.php';
             $adldap = new adLDAP();
             if ($adldap->authenticate($this->column_fields["user_name"], $user_password)) {
                 return true;
             } else {
                 return false;
             }
             break;
         default:
             $this->log->debug("Using integrated/SQL authentication");
             $query = "SELECT crypt_type FROM {$this->table_name} WHERE user_name=?";
             $result = $this->db->requirePsSingleResult($query, array($usr_name), false);
             if (empty($result)) {
                 return false;
             }
             $crypt_type = $this->db->query_result($result, 0, 'crypt_type');
             $encrypted_password = $this->encrypt_password($user_password, $crypt_type);
             $maxFailedLoginAttempts = GlobalVariable::getVariable('Application_MaxFailedLoginAttempts', 5);
             $query = "SELECT * from {$this->table_name} where user_name=? AND user_password=?";
             $params = array($usr_name, $encrypted_password);
             $cnuser = $this->db->getColumnNames($this->table_name);
             if (in_array('failed_login_attempts', $cnuser)) {
                 $query .= ' AND COALESCE(failed_login_attempts,0)<?';
                 $params[] = $maxFailedLoginAttempts;
             }
             $result = $this->db->requirePsSingleResult($query, $params, false);
             if (empty($result)) {
                 return false;
             } else {
                 return true;
             }
             break;
     }
     return false;
 }
Esempio n. 23
0
/**
 * Check user against AD
 */
function checkADLogin($username, $password)
{
    /* get All settings */
    $settings = getAllSettings();
    //include login script
    include dirname(__FILE__) . "/adLDAP/src/adLDAP.php";
    //open connection
    try {
        //get settings for connection
        $ad = getADSettings();
        //AD
        $adldap = new adLDAP(array('base_dn' => $ad['base_dn'], 'account_suffix' => $ad['account_suffix'], 'domain_controllers' => $ad['domain_controllers'], 'use_ssl' => $ad['use_ssl'], 'use_tls' => $ad['use_tls'], 'ad_port' => $ad['ad_port']));
        // set OpenLDAP flag
        if ($settings['domainAuth'] == "2") {
            $adldap->setUseOpenLDAP(true);
        }
    } catch (adLDAPException $e) {
        die('<div class="alert alert-error">' . $e . '</div>');
    }
    //user authentication
    $authUser = $adldap->authenticate($username, $password);
    if ($authUser == true) {
        global $db;
        $database = new database($db['host'], $db['user'], $db['pass'], $db['name']);
        $query = "SELECT id FROM users WHERE username = '******';";
        $user_id = $database->getRow($query);
        if (count($user_id) == 0) {
            $real_name = str_replace('.', ' ', $username);
            $real_name = ucwords($real_name);
            $email = $username . "@enovance.com";
            $query = "INSERT INTO users (username, role, real_name, email, domainUser, lang) VALUES ('{$username}', 'Administrator', '{$real_name}', '{$email}', 1, 1);";
            $database->executeQuery($query);
            $user_id = $database->insert_id;
            if (count($user_id) > 0) {
                updateLogTable('Created user ' . $username . ' successfully', "", 0);
            }
        }
        $database->close();
        if (count($user_id) > 0) {
            updateLogTable('User ' . $username . ' authenticated against AD.', "", 0);
            return 'ok';
        } else {
            updateLogTable('Failed to create user .' . $username, "", 2);
            return "Failed to creater user {$username}";
        }
    } else {
        updateLogTable('User ' . $username . ' failed to authenticate against AD.', "", 2);
        $err = $adldap->getLastError();
        return 'Failed to authenticate user via AD!';
    }
}
Esempio n. 24
0
<?php

/*$ldap['user']              = '******'; //'sanvtbouser';
$ldap['pass']              = '******'; //'Datawarehous3';  
$ldap['host']              = '10.40.3.97'; // nombre del host o servidor  
$ldap['port']              = 389; // puerto del LDAP en el servidor  
$ldap['dn']                = 'uid='.$ldap['user'].',OU=GEOI,OU=VP-IT,OU=CB,OU=NUEVATEL,OU=Servicios,OU=Usuarios,DC=nuevatel,DC=net'; // modificar respecto a los valores del LDAP  
$ldap['base']              = 'DC=nuevatel,DC=net';  
*/
require_once dirname(__FILE__) . '/adLDAP.php';
$options["domain_controllers"] = array("10.40.3.97", "10.20.3.97", "10.30.3.97");
$user = '******';
$password = '******';
$options["ad_username"] = $user;
//el usuario de active directory
$options["ad_password"] = $password;
$options["use_ssl"] = false;
$ldap = new adLDAP();
$aut = $ldap->authenticate($user, $password);
if ($aut) {
    echo 'ok';
} else {
    echo 'error';
}
Esempio n. 25
0
 /**
  * Mail enable a contact
  * Allows email to be sent to them through Exchange
  * 
  * @param string $distinguishedname The contact to mail enable
  * @param string $emailaddress The email address to allow emails to be sent through
  * @param string $mailnickname The mailnickname for the contact in Exchange.  If NULL this will be set to the display name
  * @return bool
  */
 public function contactMailEnable($distinguishedName, $emailAddress, $mailNickname = NULL)
 {
     return $this->adldap->exchange()->contactMailEnable($distinguishedName, $emailAddres, $mailNickname);
 }
Esempio n. 26
0
<?php

/*
Test for the new user collections object
*/
//error_reporting(E_ALL ^ E_NOTICE);
include dirname(__FILE__) . '/../lib/adLDAP/adLDAP.php';
try {
    $adldap = new adLDAP($options);
} catch (adLDAPException $e) {
    echo $e;
    exit;
}
echo "<pre>\n";
$collection = $adldap->user()->infoCollection('username');
print_r($collection->memberOf);
print_r($collection->displayName);
 /**
  * Test la connexion à l'ad
  * @param array $valeur
  * $valeur['login']
  * $valeur['passwd']
  * $valeur['dc']
  * $valeur['suffix']
  * $valeur['serveur']
  */
 function testerAD($valeur)
 {
     // instanciation de adldap
     $cheminAdldap = $this->getAbsolutePath() . "adldap";
     require_once $cheminAdldap . '/adLDAP.php';
     $serveur[0] = $valeur['serveur'];
     $adldap = new adLDAP(array('base_dn' => $valeur['dc'], 'account_suffix' => $valeur['suffix'], 'domain_controllers' => $serveur));
     $authUser = $adldap->authenticate($valeur['login'], $valeur['passwd']);
     $adldap->close();
     if ($authUser == true) {
         echo "Test de connexion réussit";
     } else {
         echo "Test de connexion échoué";
     }
 }
Esempio n. 28
0
<?php

/*
Test for the new user collections object
*/
//error_reporting(E_ALL ^ E_NOTICE);
include dirname(__FILE__) . "/../src/adLDAP.php";
try {
    $adldap = new adLDAP($options);
} catch (adLDAPException $e) {
    echo $e;
    exit;
}
echo "<pre>\n";
$collection = $adldap->group()->infoCollection('groupname');
print_r($collection->member);
print_r($collection->description);
Esempio n. 29
0
 /**
  *	AD (Active directory) authentication function
  *
  *	Authenticates users against MS Active Directory
  *	Using library > adLDAP - LDAP Authentication with PHP for Active Directory
  *	http://adldap.sourceforge.net
  *
  * @access private
  * @param mixed $username
  * @param mixed $password
  * @return void
  */
 private function auth_AD($username, $password)
 {
     # adLDAP script
     require dirname(__FILE__) . "/../adLDAP/src/adLDAP.php";
     # open connection
     try {
         $ad = json_decode($this->authmethodparams, true);
         // parse settings for LDAP connection and store them to array
         # set controllers
         $ad['domain_controllers'] = explode(";", str_replace(" ", "", $ad['domain_controllers']));
         # Initialize AD class
         $adldap = new adLDAP(array('base_dn' => @$ad['base_dn'], 'account_suffix' => @$ad['account_suffix'], 'domain_controllers' => @$ad['domain_controllers'], 'use_ssl' => @$ad['use_ssl'], 'use_tls' => @$ad['use_tls'], 'ad_port' => @$ad['ad_port']));
         # set OpenLDAP flag
         if ($this->ldap) {
             $adldap->setUseOpenLDAP(true);
         }
     } catch (adLDAPException $e) {
         $this->Log->write("AD connect error", "Failed to connect to AD: " . $e->getMessage(), 2, $username);
         $this->Result->show("danger", _("Error: ") . $e->getMessage(), true);
     }
     # authenticate
     if ($adldap->authenticate($username, $password)) {
         # save to session
         $this->write_session_parameters();
         $this->Log->write("AD login", "User " . $this->user->real_name . " logged in via AD", 0, $username);
         $this->Result->show("success", _("AD Login successful"));
         # write last logintime
         $this->update_login_time();
         # remove possible blocked IP
         $this->block_remove_entry();
     } else {
         if (@$authAD == 'Failed to connect to AD!') {
             $this->Log->write("AD login", "Failed to connect to AD server", 2, $username);
             $this->Result->show("danger", _("Failed to connect to AD server"), true);
         } else {
             if (@$authAD == 'Failed to authenticate user via AD!') {
                 # add blocked count
                 $this->block_ip();
                 $this->Log->write("AD login", "User {$username} failed to authenticate against AD", 1, $username);
                 $this->Result->show("danger", _("Failed to authenticate user against AD"), true);
             } else {
                 # add blocked count
                 $this->block_ip();
                 $this->Log->write("AD login", "User {$username} failed to authenticate against AD", 1, $username);
                 $this->Result->show("danger", _("Invalid username or password"), true);
             }
         }
     }
 }
Esempio n. 30
0
    /**
     * Checks the config.php AUTHCFG value for login type and forks off to the proper module
     *
     * @param string $user_password - The password of the user to authenticate
     * @return true if the user is authenticated, false otherwise
     */
    function doLogin($user_password) {
        global $AUTHCFG;
        $usr_name = $this->column_fields["user_name"];

        switch (strtoupper($AUTHCFG['authType'])) {
            case 'LDAP':
                $this->log->debug("Using LDAP authentication");
                require_once('modules/Users/authTypes/LDAP.php');
                $result = ldapAuthenticate($this->column_fields["user_name"], $user_password);
                if ($result == NULL) {
                    return false;
                } else {
                    return true;
                }
                break;

            case 'AD':
                $this->log->debug("Using Active Directory authentication");
                require_once('modules/Users/authTypes/adLDAP.php');
                $adldap = new adLDAP();
                if ($adldap->authenticate($this->column_fields["user_name"],$user_password)) {
                    return true;
                } else {
                    return false;
                }
                break;

            default:
                $this->log->debug("Using integrated/SQL authentication");
                $query = "SELECT crypt_type, user_name FROM $this->table_name WHERE user_name=?";
                $result = $this->db->requirePsSingleResult($query, array($usr_name), false);
                if (empty($result)) {
                    return false;
                }
                $crypt_type = $this->db->query_result($result, 0, 'crypt_type');
				$this->column_fields["user_name"] = $this->db->query_result($result, 0, 'user_name');
                $encrypted_password = $this->encrypt_password($user_password, $crypt_type);
                $query = "SELECT 1 from $this->table_name where user_name=? AND user_password=? AND status = ?";
                $result = $this->db->requirePsSingleResult($query, array($usr_name, $encrypted_password, 'Active'), false);
                if (empty($result)) {
                    return false;
                } else {
                    return true;
                }
                break;
        }
        return false;
    }