コード例 #1
6
ファイル: Utlookup.php プロジェクト: pkeane/humptydumpty
 public static function lookup($query, $type)
 {
     $person_array = array();
     $x500 = ldap_connect('ldap.utexas.edu');
     $bind = ldap_bind($x500);
     $dn = "ou=people,dc=directory,dc=utexas,dc=edu";
     $filter = "{$type}={$query}";
     $ldap_result = @ldap_search($x500, $dn, $filter);
     $attributes = array('eid' => 'uid', 'email' => 'mail', 'name' => 'cn', 'firstname' => 'givenname', 'lastname' => 'sn', 'office' => 'utexasedupersonofficelocation', 'phone' => 'telephonenumber', 'title' => 'title', 'unit' => 'ou');
     if ($ldap_result) {
         $entry_array = ldap_get_entries($x500, $ldap_result);
         for ($i = 0; $i < count($entry_array) - 1; $i++) {
             $person = array();
             if ($entry_array[$i]) {
                 $eid = $entry_array[$i]['uid'][0];
                 foreach ($attributes as $label => $att) {
                     if (isset($entry_array[$i][$att])) {
                         $person[$label] = $entry_array[$i][$att][0];
                     } else {
                         $person[$label] = '';
                     }
                 }
             }
             $person_array[] = $person;
         }
         ldap_close($x500);
     }
     return $person_array;
 }
コード例 #2
1
ファイル: class.PHPLdap.php プロジェクト: bayugyug/LDAP-Api
 /**
  * method to connect to the ldap server
  */
 public function connect()
 {
     $this->connection = ldap_connect($this->LDAPServer);
     ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($this->connection, LDAP_OPT_REFERRALS, 0);
     $ldap_bind = ldap_bind($this->connection, $this->LDAPDomain . "\\" . $this->LDAPUser, $this->LDAPPassword);
 }
コード例 #3
0
ファイル: ldap.class.php プロジェクト: guillaum3f/codie
 protected function open()
 {
     $bind = \ldap_connect($this->ldap_server);
     \ldap_set_option($this->bind, LDAP_OPT_PROTOCOL_VERSION, 3);
     \ldap_bind($bind, $this->admin_user . ',' . $this->base_dn, $this->admin_password);
     $this->bind = $bind;
 }
コード例 #4
0
 /**
  * Initializes the backend to perform the search
  * Connects to the LDAP server using the values from the configuration
  *
  *
  * @access public
  * @return
  * @throws StatusException
  */
 public function BackendSearchLDAP()
 {
     if (!function_exists("ldap_connect")) {
         throw new StatusException("BackendSearchLDAP(): php-ldap is not installed. Search aborted.", SYNC_SEARCHSTATUS_STORE_SERVERERROR, null, LOGLEVEL_FATAL);
     }
     // connect to LDAP
     $this->connection = @ldap_connect(LDAP_HOST, LDAP_PORT);
     @ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
     // Authenticate
     if (constant('ANONYMOUS_BIND') === true) {
         if (!@ldap_bind($this->connection)) {
             $this->connection = false;
             throw new StatusException("BackendSearchLDAP(): Could not bind anonymously to server! Search aborted.", SYNC_SEARCHSTATUS_STORE_CONNECTIONFAILED, null, LOGLEVEL_ERROR);
         }
     } else {
         if (constant('LDAP_BIND_USER') != "") {
             if (!@ldap_bind($this->connection, LDAP_BIND_USER, LDAP_BIND_PASSWORD)) {
                 $this->connection = false;
                 throw new StatusException(sprintf("BackendSearchLDAP(): Could not bind to server with user '%s' and specified password! Search aborted.", LDAP_BIND_USER), SYNC_SEARCHSTATUS_STORE_ACCESSDENIED, null, LOGLEVEL_ERROR);
             }
         } else {
             // it would be possible to use the users login and password to authenticate on the LDAP server
             // the main $backend has to keep these values so they could be used here
             $this->connection = false;
             throw new StatusException("BackendSearchLDAP(): neither anonymous nor default bind enabled. Other options not implemented.", SYNC_SEARCHSTATUS_STORE_CONNECTIONFAILED, null, LOGLEVEL_ERROR);
         }
     }
 }
コード例 #5
0
ファイル: index11111.php プロジェクト: BrutalAndSick/scrap
function login_ad($user_, $pass_, $tipo_)
{
    //Comienzo la conexión al servidor para tomar los datos de active directory
    $host = get_config('host');
    $puerto = get_config('puerto');
    $filter = "sAMAccountName=" . $user_ . "*";
    $attr = array("displayname", "mail", "givenname", "sn", "useraccountcontrol");
    $dn = get_config('dn');
    $conex = ldap_connect($host, $puerto) or die("No ha sido posible conectarse al servidor");
    if (!ldap_set_option($conex, LDAP_OPT_PROTOCOL_VERSION, 3)) {
        echo "<br>Failed to set protocol version to 3";
    }
    if ($conex) {
        $dominio = get_config("dominio");
        $r = @ldap_bind($conex, $user_ . $dominio, $pass_);
        $existe = get_perfil($user_, $tipo_);
        if ($r && count($existe) > 0) {
            //LOGIN CORRECTO
            $result = ldap_search($conex, $dn, $filter, $attr);
            $entries = ldap_get_entries($conex, $result);
            for ($i = 0; $i < $entries["count"]; $i++) {
                $nombre = fix_data(utf8_decode($entries[$i]["givenname"][0]));
                $apellidos = fix_data(utf8_decode($entries[$i]["sn"][0]));
                $email = fix_data($entries[$i]["mail"][0]);
                //Acutalizar información desde AD en la tabla de empleados
                $s_ = "update empleados set nombre='{$nombre}', apellidos='{$apellidos}', mail='{$email}' where id='{$existe['id']}'";
                $r_ = mysql_query($s_);
                session_name("loginUsuario");
                session_start();
                $_SESSION['NAME'] = $nombre . " " . $apellidos;
                $_SESSION['USER'] = $user_;
                $_SESSION['IDEMP'] = $existe['id'];
                $_SESSION['AUSENCIA'] = get_ausencia($existe['id']);
                $_SESSION['DEPTO'] = $existe['depto'];
                $_SESSION['TYPE'] = $tipo_;
            }
            switch ($tipo_) {
                case "administrador":
                    header("Location: admin/inicio.php");
                    break;
                case "capturista":
                    header("Location: capturista/inicio.php");
                    break;
                case "autorizador":
                    header("Location: autorizador/scrap_firmar.php");
                    break;
                case "reportes":
                    header("Location: reportes/rep_general.php?op=listado");
                    break;
            }
        } else {
            echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=index.php?error=2&user_={$user_}&tipo_={$tipo_}\">";
            exit;
        }
        ldap_close($conex);
    } else {
        echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=index.php?error=3&user_={$user_}&tipo_={$tipo_}\">";
        exit;
    }
}
コード例 #6
0
ファイル: LdapPerson.php プロジェクト: billdueber/resources
 public function __construct($userKey)
 {
     $config = new Configuration();
     //try to connect to ldap if the settings are entered
     if ($config->ldap->host) {
         //If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and set this parameter as ldaps://hostname/.
         //note that connect happens regardless if host is valid
         $ds = ldap_connect($config->ldap->host);
         //may need ldap_bind( $ds, $username, $password )
         $bd = ldap_bind($ds) or die("<br /><h3>" . _("Could not connect to ") . $config->ldap->host . "</h3>");
         if ($bd) {
             $filter = $config->ldap->search_key . "=" . $userKey;
             $sr = ldap_search($ds, $config->ldap->base_dn, $filter);
             if ($entries = ldap_get_entries($ds, $sr)) {
                 $entry = $entries[0];
                 $fieldNames = array('fname', 'lname', 'email', 'phone', 'department', 'title', 'address');
                 foreach ($fieldNames as $fieldName) {
                     $configName = $fieldName . '_field';
                     $this->{$fieldName} = $entry[$config->ldap->{$configName}][0];
                 }
                 $this->fullname = addslashes($this->fname . ' ' . $this->lname);
             }
             ldap_close($ds);
         }
     }
 }
コード例 #7
0
ファイル: etape_ldap4.php プロジェクト: nursit/SPIP
function install_etape_ldap4_dist()
{
    $adresse_ldap = _request('adresse_ldap');
    $login_ldap = _request('login_ldap');
    $pass_ldap = _request('pass_ldap');
    $port_ldap = _request('port_ldap');
    $base_ldap = _request('base_ldap');
    $base_ldap_text = _request('base_ldap_text');
    if (!$base_ldap) {
        $base_ldap = $base_ldap_text;
    }
    echo install_debut_html();
    $ldap_link = ldap_connect($adresse_ldap, $port_ldap);
    @ldap_bind($ldap_link, $login_ldap, $pass_ldap);
    // Essayer de verifier le chemin fourni
    $r = @ldap_compare($ldap_link, $base_ldap, "objectClass", "");
    $fail = ldap_errno($ldap_link) == 32;
    if ($fail) {
        echo info_etape(_T('info_chemin_acces_annuaire')), info_progression_etape(3, 'etape_ldap', 'install/', true), "<div class='error'><p><b>" . _T('avis_operation_echec') . "</b></p><p>" . _T('avis_chemin_invalide_1'), " (<tt>" . htmlspecialchars($base_ldap) . "</tt>) " . _T('avis_chemin_invalide_2') . "</p></div>";
    } else {
        info_etape(_T('info_reglage_ldap'));
        echo info_progression_etape(4, 'etape_ldap', 'install/');
        $statuts = liste_statuts_ldap();
        $statut_ldap = defined('_INSTALL_STATUT_LDAP') ? _INSTALL_STATUT_LDAP : $GLOBALS['liste_des_statuts']['info_redacteurs'];
        $res = install_propager(array('adresse_ldap', 'port_ldap', 'login_ldap', 'pass_ldap', 'protocole_ldap', 'tls_ldap')) . "<input type='hidden' name='etape' value='ldap5' />" . "<input type='hidden' name='base_ldap' value='" . htmlentities($base_ldap) . "' />" . fieldset(_T('info_statut_utilisateurs_1'), array('statut_ldap' => array('label' => _T('info_statut_utilisateurs_2') . '<br />', 'valeur' => $statut_ldap, 'alternatives' => $statuts))) . install_ldap_correspondances() . bouton_suivant();
        echo generer_form_ecrire('install', $res);
    }
    echo install_fin_html();
}
コード例 #8
0
ファイル: ldap.inc.php プロジェクト: alvunera/FreeNats-PlugIn
 function DoTest($testname, $param, $hostname, $timeout, $params)
 {
     global $NATS;
     $url = $params[0];
     $bind = $params[1];
     $pasw = $params[2];
     $base = $params[3];
     $filter = $params[4];
     $ds = ldap_connect($url);
     if (!$ds) {
         return -2;
     }
     $ldap = $bind && $pasw ? ldap_bind($ds, $bind, $pasw) : ldap_bind($ds);
     if (!$ldap) {
         return -1;
     }
     if ($base && $filter) {
         $search = ldap_search($ds, $base, $filter);
         $val = ldap_count_entries($ds, $search);
     } else {
         $val = 1;
     }
     ldap_close($ds);
     return $val;
 }
コード例 #9
0
ファイル: Manager.php プロジェクト: vionox/sentinel-ldap
 protected function connect($ldap_host, $ldap_port)
 {
     if ($ldap_host && $ldap_port) {
         return @ldap_connect($ldap_host, $ldap_port);
     }
     return false;
 }
コード例 #10
0
ファイル: accorder_comptes_lcs.php プロジェクト: rhertzog/lcs
function search_uidspip ($filter,$ldap_server, $ldap_port, $dn) {
  global  $ldap_grp_attr;
  
  // LDAP attributs
  $ldap_grp_attr = array (
    "cn",
    "memberuid"  );

  $ds = @ldap_connect ( $ldap_server, $ldap_port );
  if ( $ds ) {
    $r = @ldap_bind ( $ds ); // Bind anonyme
    if ($r) {
      $result=@ldap_list ($ds, $dn["groups"], $filter, $ldap_grp_attr);
      if ($result) {
        $info = ldap_get_entries( $ds, $result );
        if ($info["count"]) {
          // Stockage des logins des membres des classes
          //  dans le tableau $ret
          $init=0;
          for ($loop=0; $loop < $info["count"]; $loop++) {
            $group=split ("[\_\]",$info[$loop]["cn"][0],2);
            for ( $i = 0; $i < $info[$loop]["memberuid"]["count"]; $i++ ) {
              $ret[$init]["uid"] = $info[$loop]["memberuid"][$i];
              $ret[$init]["cat"] = $group[0];
              $init++;
            }
          }
        }
        ldap_free_result ( $result );
      }
    } 
    @ldap_close ( $ds );
  } 
  return $ret;
}
コード例 #11
0
ファイル: Ldap.php プロジェクト: jbirdkerr/snipe-it
 /**
  * Makes a connection to LDAP using the settings in Admin > Settings.
  *
  * @author [A. Gianotto] [<*****@*****.**>]
  * @since [v3.0]
  * @return connection
  */
 public static function connectToLdap()
 {
     $ldap_host = Setting::getSettings()->ldap_server;
     $ldap_version = Setting::getSettings()->ldap_version;
     $ldap_server_cert_ignore = Setting::getSettings()->ldap_server_cert_ignore;
     $ldap_use_tls = Setting::getSettings()->ldap_tls;
     // If we are ignoring the SSL cert we need to setup the environment variable
     // before we create the connection
     if ($ldap_server_cert_ignore == '1') {
         putenv('LDAPTLS_REQCERT=never');
     }
     // If the user specifies where CA Certs are, make sure to use them
     if (env("LDAPTLS_CACERT")) {
         putenv("LDAPTLS_CACERT=" . env("LDAPTLS_CACERT"));
     }
     $connection = @ldap_connect($ldap_host);
     if (!$connection) {
         throw new Exception('Could not connect to LDAP server at ' . $ldap_host . '. Please check your LDAP server name and port number in your settings.');
     }
     // Needed for AD
     ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
     ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldap_version);
     if ($ldap_use_tls == '1') {
         ldap_start_tls($connection);
     }
     return $connection;
 }
コード例 #12
0
ファイル: LDAP.php プロジェクト: hugcoday/wiki
 /**
  * ->_init()
  * connect and bind to the LDAP host
  */
 function _init()
 {
     if ($this->_ldap = ldap_connect(LDAP_AUTH_HOST)) {
         // must be a valid LDAP server!
         global $LDAP_SET_OPTION;
         if (!empty($LDAP_SET_OPTION)) {
             foreach ($LDAP_SET_OPTION as $key => $value) {
                 //if (is_string($key) and defined($key))
                 //    $key = constant($key);
                 ldap_set_option($this->_ldap, $key, $value);
             }
         }
         if (LDAP_AUTH_USER) {
             if (LDAP_AUTH_PASSWORD) {
                 // Windows Active Directory Server is strict
                 $r = ldap_bind($this->_ldap, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD);
             } else {
                 $r = ldap_bind($this->_ldap, LDAP_AUTH_USER);
             }
         } else {
             $r = true;
         }
         // anonymous bind allowed
         if (!$r) {
             $this->_free();
             trigger_error(sprintf(_("Unable to bind LDAP server %s using %s %s"), LDAP_AUTH_HOST, LDAP_AUTH_USER, LDAP_AUTH_PASSWORD), E_USER_WARNING);
             return false;
         }
         return $this->_ldap;
     } else {
         return false;
     }
 }
コード例 #13
0
 public function lookupUser($credentials)
 {
     $username = $credentials['username'];
     $password = $credentials['password'];
     $this->log('Ldap: looking up user "' . $username . '" in LDAP server ');
     $sourceConfig = $this->source;
     $server = parse_url($sourceConfig['url']);
     if (empty($server['host'])) {
         return false;
         // oops
     }
     $connect = ldap_connect($server['host'], empty($server['port']) ? 389 : $server['port']);
     ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
     //$connect=ldap_connect($server['host']);
     $this->log('Connected');
     if (!$connect) {
         throw new PHPDS_exception('Unable to connect to the LDAP server');
     }
     if ($sourceConfig['namePattern']) {
         $username = PU_sprintfn($sourceConfig['namePattern'], array($username));
     }
     if (!@ldap_bind($connect, $username, $password)) {
         return false;
         // if we can't bind it's likely the user is unknown or the password is wrong
     }
     $this->log('Bound');
     return true;
 }
コード例 #14
0
ファイル: ldap.inc.php プロジェクト: skive/observium
function ldap_init()
{
    global $ds, $config;
    if (!is_resource($ds)) {
        print_debug("LDAP[Connecting to " . implode(",", $config['auth_ldap_server']) . "]");
        $ds = @ldap_connect(implode(",", $config['auth_ldap_server']), $config['auth_ldap_port']);
        print_debug("LDAP[Connected]");
        if ($config['auth_ldap_starttls'] && ($config['auth_ldap_starttls'] == 'optional' || $config['auth_ldap_starttls'] == 'require')) {
            $tls = ldap_start_tls($ds);
            if ($config['auth_ldap_starttls'] == 'require' && $tls == FALSE) {
                session_logout();
                print_error("Fatal error: LDAP TLS required but not successfully negotiated [" . ldap_error($ds) . "]");
                exit;
            }
        }
        if ($config['auth_ldap_referrals']) {
            ldap_set_option($ds, LDAP_OPT_REFERRALS, $config['auth_ldap_referrals']);
            print_debug("LDAP[Referrals][Set to " . $config['auth_ldap_referrals'] . "]");
        } else {
            ldap_set_option($ds, LDAP_OPT_REFERRALS, FALSE);
            print_debug("LDAP[Referrals][Disabled]");
        }
        if ($config['auth_ldap_version']) {
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $config['auth_ldap_version']);
            print_debug("LDAP[Version][Set to " . $config['auth_ldap_version'] . "]");
        }
    }
}
コード例 #15
0
function get_ldap_members($group, $user, $password)
{
    global $ldap_host;
    global $ldap_dn;
    $LDAPFieldsToFind = array("member");
    print "{$ldap_host} {$ldap_dn}\n";
    $ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
    // OPTIONS TO AD
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    ldap_bind($ldap, $user, $password) or die("Could not bind to LDAP");
    //check if group is just a name or an ldap string
    $group_cn = preg_match("/cn=/i", $group) ? $group : "cn={$group}";
    $results = ldap_search($ldap, $ldap_dn, $group_cn, $LDAPFieldsToFind);
    $member_list = ldap_get_entries($ldap, $results);
    $group_member_details = array();
    if (is_array($member_list[0])) {
        foreach ($member_list[0] as $list) {
            if (is_array($list)) {
                foreach ($list as $member) {
                    $member_dn = explode_dn($member);
                    $member_cn = str_replace("CN=", "", $member_dn[0]);
                    $member_search = ldap_search($ldap, $ldap_dn, "(CN=" . $member_cn . ")");
                    $member_details = ldap_get_entries($ldap, $member_search);
                    $group_member_details[] = array($member_details[0]['samaccountname'][0], $member_details[0]['displayname'][0], $member_details[0]['useraccountcontrol'][0]);
                }
            }
        }
    }
    ldap_close($ldap);
    array_shift($group_member_details);
    return $group_member_details;
    ldap_unbind($ldap);
}
コード例 #16
0
 /**
  * Logs the user in to the TMT through LDAP
  *
  * Expects the netId and password fields to be set in the request
  */
 public function ldap($params)
 {
     session_start();
     $netId = isset($params['request']['netId']) ? $params['request']['netId'] : null;
     $password = isset($params['request']['password']) ? $params['request']['password'] : null;
     if ($netId == null || $password == null) {
         session_destroy();
         header('Location: /landing');
         exit;
     }
     $link = \ldap_connect(getenv("LDAPURL"), 389);
     if ($link) {
         \ldap_set_option($link, LDAP_OPT_SIZELIMIT, 2);
         $authenticated = @\ldap_bind($link, 'uid=' . $netId . ',ou=People,o=byu.edu', $password);
         if ($authenticated) {
             $_SESSION['user'] = $netId;
             $_SESSION['ldap'] = true;
             header('Location: /');
             exit;
         } else {
             session_destroy();
             $this->user['netId'] = null;
             $this->render("helpers/loginFail");
             exit;
         }
     } else {
         // Unable to connect to LDAP, return to landing page
         session_destroy();
         header('Location: /landing');
         exit;
     }
 }
コード例 #17
0
ファイル: ldap-functions.php プロジェクト: ddrmoscow/queXS
function ldap_getCnx($server_id = null)
{
    global $ldap_server;
    if (is_null($server_id)) {
        return False;
    } else {
        if ($ldap_server[$server_id]['protoversion'] == 'ldapv3' && $ldap_server[$server_id]['encrypt'] != 'ldaps') {
            $ds = ldap_connect($ldap_server[$server_id]['server'], $ldap_server[$server_id]['port']);
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
            if (!$ldap_server[$server_id]['referrals']) {
                ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
            }
            if ($ldap_server[$server_id]['encrypt'] == 'start-tls') {
                ldap_start_tls($ds);
            }
        } elseif ($ldap_server[$server_id]['protoversion'] == 'ldapv2') {
            if ($ldap_server[$server_id]['encrypt'] == 'ldaps') {
                $ds = ldap_connect("ldaps://" . $ldap_server[$server_id]['server'], $ldap_server[$server_id]['port']);
            } else {
                $ds = ldap_connect($ldap_server[$server_id]['server'], $ldap_server[$server_id]['port']);
            }
            if (!$ldap_server[$server_id]['referrals']) {
                ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
            }
        }
        return $ds;
    }
}
コード例 #18
0
 function authenticate()
 {
     error_reporting(0);
     //stops it from sending errors about not being able to bind when invalid username/password entered.
     if (!isset($_SERVER['PHP_AUTH_USER'])) {
         //this sets username and password to an invalid setting so that it doesn't bind anonomously
         $user = "******";
         $pass = "******";
     } else {
         $user = $_SERVER['PHP_AUTH_USER'];
         $pass = $_SERVER['PHP_AUTH_PW'];
     }
     $ldap = ldap_connect('ad.hud.ac.uk');
     if (!$ldap) {
         print "<br>connection error";
         exit;
     }
     $ad_validate = ldap_bind($ldap, $user . '@ad.hud.ac.uk', $pass);
     //check if AD credentials are correct
     $this->db_connect();
     $registered_user = mysql_query("SELECT userID, dept, accesslevel FROM users WHERE userID = '" . $user . "'");
     $app_validate = mysql_num_rows($registered_user);
     //check if user is registered with the system
     if (!$ad_validate || !$app_validate) {
         header('WWW-Authenticate: Basic realm="ILP"');
         header('HTTP/1.0 401 Unauthorized');
         die("Not authorized, contact <a href='mailto:i.mcnaught@hud.ac.uk'>Ian McNaught</a> for access");
         exit;
     }
     $user = mysql_fetch_assoc($registered_user);
     session_start();
     $_SESSION['user'] = $user;
 }
コード例 #19
0
ファイル: CLdap.php プロジェクト: TonywalkerCN/Zabbix
 public function connect()
 {
     // connection already established
     if ($this->ds) {
         return true;
     }
     $this->bound = 0;
     if (!($this->ds = ldap_connect($this->cnf['host'], $this->cnf['port']))) {
         error('LDAP: couldn\'t connect to LDAP server.');
         return false;
     }
     // set protocol version and dependend options
     if ($this->cnf['version']) {
         if (!ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, $this->cnf['version'])) {
             error('Setting LDAP Protocol version ' . $this->cnf['version'] . ' failed.');
         } else {
             // use TLS (needs version 3)
             if (isset($this->cnf['starttls']) && !ldap_start_tls($this->ds)) {
                 error('Starting TLS failed.');
             }
             // needs version 3
             if (!zbx_empty($this->cnf['referrals']) && !ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $this->cnf['referrals'])) {
                 error('Setting LDAP referrals to off failed.');
             }
         }
     }
     // set deref mode
     if (isset($this->cnf['deref']) && !ldap_set_option($this->ds, LDAP_OPT_DEREF, $this->cnf['deref'])) {
         error('Setting LDAP Deref mode ' . $this->cnf['deref'] . ' failed.');
     }
     return true;
 }
コード例 #20
0
ファイル: ldap-auth.php プロジェクト: le9i0nx/ansible-root
function ldap_auth()
{
    $ldap_server = 'ldap://127.0.0.1/';
    $ldap_domain = 'dc=rugion,dc=ru';
    //$ldap_userbase = 'ou=users,ou=chelyabinsk,' . $ldap_domain;
    //$ldap_user = '******' . $_SERVER['PHP_AUTH_USER'] . ',' . $ldap_userbase;
    $ldap_user = '******';
    $ldap_pass = $_SERVER['PHP_AUTH_PW'];
    $ldapconn_s = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
    ldap_set_option($ldapconn_s, LDAP_OPT_PROTOCOL_VERSION, 3);
    if ($ldapconn_s) {
        $ldapbind_s = @ldap_bind($ldapconn_s);
        $result = ldap_search($ldapconn_s, $ldap_domain, "(&(uid=" . $_SERVER['PHP_AUTH_USER'] . ")(objectClass=sambaSamAccount)(!(sambaAcctFlags=[DU ])))");
        $info = ldap_get_entries($ldapconn_s, $result);
        $ldap_user = $info[0]["dn"];
    }
    ldap_close($ldapconn_s);
    // connect to ldap server
    $ldapconn = ldap_connect($ldap_server) or die("Could not connect to LDAP server.");
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    if ($ldapconn) {
        // try to bind/authenticate against ldap
        $ldapbind = @ldap_bind($ldapconn, $ldap_user, $ldap_pass) || forbidden();
        // "LDAP bind successful...";
        error_log("success: " . $_SERVER['REMOTE_ADDR'] . ', user: '******'PHP_AUTH_USER']);
    }
    ldap_close($ldapconn);
}
コード例 #21
0
ファイル: Ldap.php プロジェクト: DSNS-LAB/Dmail
 /**
  * Initiate LDAP connection.
  *
  * Not done in __construct(), only when a read or write action is
  * necessary.
  */
 protected function _connect()
 {
     if ($this->_ds) {
         return;
     }
     if (!($this->_ds = @ldap_connect($this->_params['server'], $this->_params['port']))) {
         throw new Turba_Exception(_("Connection failure"));
     }
     /* Set the LDAP protocol version. */
     if (!empty($this->_params['version'])) {
         @ldap_set_option($this->_ds, LDAP_OPT_PROTOCOL_VERSION, $this->_params['version']);
     }
     /* Set the LDAP deref option for dereferencing aliases. */
     if (!empty($this->_params['deref'])) {
         @ldap_set_option($this->_ds, LDAP_OPT_DEREF, $this->_params['deref']);
     }
     /* Set the LDAP referrals. */
     if (!empty($this->_params['referrals'])) {
         @ldap_set_option($this->_ds, LDAP_OPT_REFERRALS, $this->_params['referrals']);
     }
     /* Start TLS if we're using it. */
     if (!empty($this->_params['tls']) && !@ldap_start_tls($this->_ds)) {
         throw new Turba_Exception(sprintf(_("STARTTLS failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
     }
     /* Bind to the server. */
     if (isset($this->_params['bind_dn']) && isset($this->_params['bind_password'])) {
         $error = !@ldap_bind($this->_ds, $this->_params['bind_dn'], $this->_params['bind_password']);
     } else {
         $error = !@ldap_bind($this->_ds);
     }
     if ($error) {
         throw new Turba_Exception(sprintf(_("Bind failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
     }
 }
コード例 #22
0
ファイル: LoginAD.class.php プロジェクト: nemiah/poolPi
 private static function getADConnection($username = null, $password = null)
 {
     if (!function_exists("ldap_connect")) {
         return null;
     }
     $LD = LoginData::get("ADServerUserPass");
     if ($LD == null) {
         return null;
     }
     $adServer = "ldap://" . $LD->A("server");
     $ex = explode("@", $LD->A("benutzername"));
     if ($username == null) {
         $username = $LD->A("benutzername");
     } else {
         $username = $username . "@" . $ex[1];
     }
     if ($password == null) {
         $password = $LD->A("passwort");
     }
     $ldap = ldap_connect($adServer);
     ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
     ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
     $bind = ldap_bind($ldap, $username, $password);
     if (!$bind) {
         throw new Exception("Keine Verbindung zu AD-Server");
     }
     return $ldap;
 }
コード例 #23
0
 private function bindLDAP($strDN, $strPWD, $bSearch)
 {
     $ldap = ldap_connect("ldaps://{$this->strHost}:636") or $ldap = false;
     if ($ldap) {
         //Connected successfully to ldap server
         $this->logwriter->debugwrite('Successfully Connected to LDAP Server');
         $res = ldap_bind($ldap, $strDN, $strPWD) or $res = false;
         if ($res) {
             //Succcessfully bound with search DN login
             $this->logwriter->debugwrite("Successfully Bound with Search DN: {$strDN} Passwd: {$strPWD}");
             return $ldap;
         } else {
             if ($bSearch) {
                 $this->failure(3, array($strDN, $strPWD, ldap_error($ldap)));
             } else {
                 $this->failure(7, array($strDN, $strPWD, ldap_error($ldap)));
             }
         }
     } else {
         if ($bSearch) {
             $this->failure(2, array($this->strHost));
         } else {
             $this->failure(6, array($this->strHost));
         }
     }
 }
コード例 #24
0
function checkAdLoginAuth($user_id, $login_passwd)
{
    //接続開始
    $ldap_conn = ldap_connect(LDAP_HOST_1, LDAP_PORT);
    if (!$ldap_conn) {
        $ldap_conn = ldap_connect("ldaps://" . LDAP_HOST_2);
    } else {
        print_r("OK" . PHP_EOL);
    }
    if (!$ldap_conn) {
        Debug_Trace("接続失敗");
        return false;
    }
    if ($ldap_conn) {
        ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
        $ldap_bind = ldap_bind($ldap_conn, "CN=" . $user_id . "," . LDAP_DN, $login_passwd);
        if ($ldap_bind) {
            Debug_Trace("ADの認証に成功しました", 3);
            return true;
        } else {
            Debug_Trace("ADの認証に失敗しました", 3);
            Debug_Trace($user_id, 3);
            return false;
        }
    } else {
        Debug_Trace('ADサーバへの接続に失敗しました');
        return false;
    }
    ldap_close($ldap_conn);
    return true;
}
コード例 #25
0
 /**
  * Constructor
  *
  * @param \Cake\Controller\ComponentRegistry $registry The Component registry used on this request.
  * @param array $config Array of config to use.
  */
 public function __construct(ComponentRegistry $registry, array $config = [])
 {
     parent::__construct($registry, $config);
     if (!defined('LDAP_OPT_DIAGNOSTIC_MESSAGE')) {
         define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x32);
     }
     if (isset($config['host']) && is_object($config['host']) && $config['host'] instanceof \Closure) {
         $config['host'] = $config['host']();
     }
     if (empty($config['host'])) {
         throw new InternalErrorException('LDAP Server not specified!');
     }
     if (empty($config['port'])) {
         $config['port'] = null;
     }
     if (isset($config['logErrors']) && $config['logErrors'] === true) {
         $this->logErrors = true;
     }
     try {
         $this->ldapConnection = ldap_connect($config['host'], $config['port']);
         if (isset($config['options']) && is_array($config['options'])) {
             foreach ($config['options'] as $option => $value) {
                 ldap_set_option($this->ldapConnection, $option, $value);
             }
         } else {
             ldap_set_option($this->ldapConnection, LDAP_OPT_NETWORK_TIMEOUT, 5);
         }
     } catch (Exception $e) {
         throw new InternalErrorException('Unable to connect to specified LDAP Server(s)!');
     }
 }
コード例 #26
0
 function dsConnect($bind = "yes")
 {
     $this->setLDAPVars();
     global $wgDS;
     global $wgDSPort;
     global $wgBindType;
     global $wgBindProxyDN;
     global $wgBindProxyPW;
     $ldap_conn = ldap_connect($wgDS, $wgDSPort);
     if (isset($ldap_conn) and $ldap_conn) {
         ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
         ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
         if ($bind == "no") {
             return $ldap_conn;
         }
         if (isset($wgBindType) and $wgBindType == "ProxyAccount") {
             if (ldap_bind($ldap_conn, $wgBindProxyDN, $wgBindProxyPW)) {
                 return $ldap_conn;
             } else {
                 return false;
             }
         } else {
             if (ldap_bind($ldap_conn)) {
                 return $ldap_conn;
             } else {
                 return false;
             }
         }
     }
     return false;
 }
コード例 #27
0
 public function getAllUsers()
 {
     // Settings for LDAP
     if ($this->container->hasParameter('ldap_host')) {
         $ldapHostname = $this->container->getParameter("ldap_host");
         $ldapPort = $this->container->getParameter("ldap_port");
         $ldapVersion = $this->container->getParameter("ldap_version");
         $baseDn = $this->container->getParameter("ldap_user_base_dn");
         $nameAttribute = $this->container->getParameter("ldap_user_name_attribute");
         $filter = "(" . $nameAttribute . "=*)";
         $connection = @ldap_connect($ldapHostname, $ldapPort);
         ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, $ldapVersion);
         $ldapListRequest = ldap_list($connection, $baseDn, $filter);
         // or throw exeption('Unable to list. LdapError: ' . ldap_error($ldapConnection));
         $ldapUserList = ldap_get_entries($connection, $ldapListRequest);
     }
     // Settings for local user database
     $repo = $this->getDoctrine()->getRepository('FOMUserBundle:User');
     $users = $repo->findAll();
     $all = array();
     if ($this->container->hasParameter('ldap_host')) {
         // Add Users from LDAP
         foreach ($ldapUserList as $ldapUser) {
             $user = new \stdClass();
             $user->getUsername = $ldapUser[$nameAttribute][0];
             $all[] = $user;
         }
     }
     // Add Mapbenderusers from database
     foreach ($users as $user) {
         $all[] = $user;
     }
     return $all;
 }
コード例 #28
0
ファイル: ldap_api.php プロジェクト: jin255ff/company_website
function ldap_connect_bind($p_binddn = '', $p_password = '')
{
    $t_ldap_server = config_get('ldap_server');
    $t_ldap_port = config_get('ldap_port');
    if (!extension_loaded('ldap')) {
        trigger_error(ERROR_LDAP_EXTENSION_NOT_LOADED, ERROR);
    }
    $t_ds = @ldap_connect($t_ldap_server, $t_ldap_port);
    if ($t_ds > 0) {
        $t_protocol_version = config_get('ldap_protocol_version');
        if ($t_protocol_version > 0) {
            ldap_set_option($t_ds, LDAP_OPT_PROTOCOL_VERSION, $t_protocol_version);
        }
        # If no Bind DN and Password is set, attempt to login as the configured
        #  Bind DN.
        if (is_blank($p_binddn) && is_blank($p_password)) {
            $p_binddn = config_get('ldap_bind_dn', '');
            $p_password = config_get('ldap_bind_passwd', '');
        }
        if (!is_blank($p_binddn) && !is_blank($p_password)) {
            $t_br = @ldap_bind($t_ds, $p_binddn, $p_password);
        } else {
            # Either the Bind DN or the Password are empty, so attempt an anonymous bind.
            $t_br = @ldap_bind($t_ds);
        }
        if (!$t_br) {
            trigger_error(ERROR_LDAP_AUTH_FAILED, ERROR);
        }
    } else {
        trigger_error(ERROR_LDAP_SERVER_CONNECT_FAILED, ERROR);
    }
    return $t_ds;
}
コード例 #29
0
ファイル: Ldap.php プロジェクト: jubinpatel/horde
 /**
  * Connect and bind to ldap server.
  *
  * @throws Ingo_Exception
  */
 protected function _connect()
 {
     if (!($ldapcn = @ldap_connect($this->_params['hostspec'], $this->_params['port']))) {
         throw new Ingo_Exception(_("Connection failure"));
     }
     /* Set the LDAP protocol version. */
     if (!empty($this->_params['version'])) {
         @ldap_set_option($ldapcn, LDAP_OPT_PROTOCOL_VERSION, $this->_params['version']);
     }
     /* Start TLS if we're using it. */
     if (!empty($this->_params['tls']) && !@ldap_start_tls($ldapcn)) {
         throw new Ingo_Exception(sprintf(_("STARTTLS failed: (%s) %s"), ldap_errno($ldapcn), ldap_error($ldapcn)));
     }
     /* Bind to the server. */
     if (isset($this->_params['bind_dn'])) {
         $bind_dn = $this->_substUser($this->_params['bind_dn']);
         $password = isset($this->_params['bind_password']) ? $this->_params['bind_password'] : $this->_params['password'];
         $bind_success = @ldap_bind($ldapcn, $bind_dn, $password);
     } else {
         $bind_success = @ldap_bind($ldapcn);
     }
     if ($bind_success) {
         return $ldapcn;
     }
     throw new Ingo_Exception(sprintf(_("Bind failed: (%s) %s"), ldap_errno($ldapcn), ldap_error($ldapcn)));
 }
コード例 #30
0
ファイル: login.php プロジェクト: DeltaWolf7/Arc
function LDAPLogin($server = "mydomain.local", $username, $password, $domain = "mydomain", $dc = "dc=mydomain,dc=local")
{
    // https://www.exchangecore.com/blog/how-use-ldap-active-directory-authentication-php/
    $ldap = ldap_connect("ldap://{$server}");
    $ldaprdn = "{$domain}\\{$username}";
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
    $bind = @ldap_bind($ldap, $ldaprdn, $password);
    if ($bind) {
        $filter = "(sAMAccountName={$username})";
        $result = ldap_search($ldap, $dc, $filter);
        ldap_sort($ldap, $result, "sn");
        $info = ldap_get_entries($ldap, $result);
        if (!isset($info[0]["mail"][0])) {
            Log::createLog("danger", "ldap", "Unable to query LDAP, check base settings.");
            return null;
        }
        $data = array();
        $data["email"] = $info[0]["mail"][0];
        $data["lastname"] = $info[0]["sn"][0];
        $data["firstname"] = $info[0]["givenname"][0];
        @ldap_close($ldap);
        return $data;
    } else {
        Log::createLog("danger", "ldap", "Error: " . ldap_error($ldap));
    }
    return null;
}