Rev 2475 | Rev 2705 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log
<?php
# $Id: ldap.php 2532 2018-04-30 03:55:35Z tom.houdayer $
/* written by steweb57, Rexy & Tom HOUDAYER */
/****************************************************************
* GLOBAL FILE PATHS *
*****************************************************************/
define('CONF_FILE', '/usr/local/etc/alcasar.conf');
/****************************************************************
* FILE reading test *
*****************************************************************/
$conf_files = array(CONF_FILE);
foreach ($conf_files as $file) {
if (!file_exists($file)) {
exit("Fichier $file non présent");
}
if (!is_readable($file)) {
exit("Vous n'avez pas les droits de lecture sur le fichier $file");
}
}
/****************************************************************
* Read CONF_FILE *
*****************************************************************/
$file_conf = fopen(CONF_FILE, 'r');
if (!$file_conf) {
exit('Error opening the file '.CONF_FILE);
}
while (!feof($file_conf)) {
$buffer = fgets($file_conf, 4096);
if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
$tmp = explode('=', $buffer, 2);
$conf[trim($tmp[0])] = trim($tmp[1]);
}
}
fclose($file_conf);
/****************************************************************
* Choice of language *
*****************************************************************/
$Language = 'en';
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$Langue = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$Language = strtolower(substr(chop($Langue[0]), 0, 2));
}
if ($Language === 'fr') { // French
$l_ldap_update = "Mise à jour des paramètres LDAP effectuée";
$l_ldap_title = "Authentification externe : LDAP";
$l_ldap_legend = "Authentification LDAP";
$l_ldap_auth_enable_label = "Éditer la configuration LDAP:";
$l_ldap_YES = "OUI";
$l_ldap_NO = "NON";
$l_ldap_server_label = "Serveur LDAP:";
$l_ldap_server_text = "Adresse IP du serveur";
$l_ldap_base_dn_label = "DN de la base:";
$l_ldap_base_dn_text = "Le DN (Distinguished Name) définit où se situent les informations des utilisateurs dans l'annuaire.<br> - Exemple LDAP: 'o=mycompany, c=FR'.<br> - Exemple AD 'cn=Users,dc=server_name,dc=localdomain'";
$l_ldap_uid_label = "Identifiant d'utilisateur (UID):";
$l_ldap_uid_text = "Clé utilisée pour rechercher un identifiant de connexion.<br> - Exemple LDAP: 'uid', 'sn', etc.<br> - Pour A.D. mettre 'sAMAccountName'.";
$l_ldap_base_filter_label = "Filtre de recherche des utilisateurs (optionnel):";
$l_ldap_base_filter_text = "Vous pouvez limiter les objets recherchés avec des filtres additionnels.<br> Exemple 'objectClass=posixGroup' ajouterait le filtre '(&(uid=username)(objectClass=posixGroup))'";
$l_ldap_user_label = "CN de l'utilisateur exploité par ALCASAR:";
$l_ldap_user_text = "CN=Common Name. Laissez vide pour utiliser un accès invité (ou anonyme). Obligatoire sur un AD.<br> - Exemple LDAP : 'uid=username,ou=my_lan,o=mycompany,c=FR'.<br> - Exemple AD : 'username' ou 'cn=username,cn=Users,dc=server_name,dc=localdomain'";
$l_ldap_password_label = "Mot de passe:";
$l_ldap_password_text = "Laissez vide pour un accès invité (ou anonyme). Obligatoire sur un AD.";
$l_ldap_submit = "Enregistrer";
$l_ldap_test_service_failed = "Service LDAP injoignable sur ce serveur (vérifiez l'@IP).";
$l_ldap_test_service_ok = "Un port 389 est actif sur ce serveur";
$l_ldap_test_connection_failed = "Connexion LDAP impossible (vérifiez le service LDAP sur ce serveur)";
$l_ldap_test_connection_ok = "Une connexion LDAP a été établie";
$l_ldap_test_bind_failed = "Echec d'authentification (vérifiez l'utilisateur et le mot de passe)";
$l_ldap_test_bind_ok = "L'authentification a réussie";
$l_ldap_test_dn_failed = "Le DN de la base semble incorrect (vérifiez le)";
$l_ldap_test_dn_ok = "Le DN de la base semble correct";
$l_ldap_error = "erreur LDAP";
$l_ldap_entries = "entrées dans la base";
$l_check = "Vérifier cette configuration";
$l_checkingConf = "Vérification de cette configuration...";
} else { // English
$l_ldap_update = "LDAP settings updated";
$l_ldap_title = "External authentication : LDAP";
$l_ldap_legend = "LDAP authentication";
$l_ldap_auth_enable_label = "Edit the LDAP configuration :";
$l_ldap_YES = "YES";
$l_ldap_NO = "NO";
$l_ldap_server_label = "LDAP server :";
$l_ldap_server_text = "IP address of the LDAP server.";
$l_ldap_base_dn_label = "DN of the base:";
$l_ldap_base_dn_text = "The DN (Distinguished Name) is used to locate the users information in the directory.<br> e.g. LDAP : 'o=MyCompany,c=US'.<br> e.g. AD : 'cn=Users,dc=server_name,dc=localdomain'";
$l_ldap_uid_label = "User IDentifier (UID):";
$l_ldap_uid_text = "Key used to search for a given login identity.<br>e.g. 'uid', 'sn', etc.. For AD use 'sAMAccountName'.";
$l_ldap_base_filter_label = "User search filter (optional):";
$l_ldap_base_filter_text = "You can further limit the searched objects with additional filters.<br> For example 'objectClass=posixGroup' would result in the use of '(&(uid=username)(objectClass=posixGroup))'";
$l_ldap_user_label = "CN of the user operated by ALCASAR:";
$l_ldap_user_text = "CN=Common Name. Leave blank to use anonymous binding. Mandatory for AD.<br> e.g. LDAP :'uid=Username,ou=my_lan,o=mycompany,c=US'.<br> e.g. AD : 'username' or 'cn=username,cn=Users,dc=server_name,dc=localdomain'";
$l_ldap_password_label = "Password:";
$l_ldap_password_text = "Leave blank to use anonymous binding. Mandatory for AD.";
$l_ldap_submit = "Save";
$l_ldap_test_service_failed = "LDAP service is not reachable on that server (check IP)";
$l_ldap_test_service_ok = "A port 389 is open on this server";
$l_ldap_test_connection_failed = "LDAP connexion failed (check the LDAP service on this server)";
$l_ldap_test_connection_ok = "A LDAP connexion is established";
$l_ldap_test_bind_failed = "LDAP authentication failed (check the LDAP user and password)";
$l_ldap_test_bind_ok = "Successful authentication";
$l_ldap_test_dn_failed = "DN of the base seems to be wrong (check it)";
$l_ldap_test_dn_ok = "DN of the base seems to be ok";
$l_ldap_error = "LDAP error";
$l_ldap_entries = "entries in the base";
$l_check = "Check this config";
$l_checkingConf = "Checking this configuration...";
}
function ldap_checkServerConfig($f_ldap_server, $f_ldap_identity, $f_ldap_password, $f_ldap_basedn, $f_ldap_uid, $f_ldap_port = 389) {
// Socket to the LDAP port of the server
if (!$sock = @fsockopen($f_ldap_server, $f_ldap_port, $num, $error, 2)) {
// no network connection
return -2;
}
fclose($sock);
// if ok, Test LDAP connection
$ldapconn = ldap_connect($f_ldap_server, $f_ldap_port);
ldap_set_option($ldapconn, LDAP_OPT_TIMELIMIT, 2);
if (!$ldapconn) {
// LDAP connection failed
return -1;
}
// if ok, test a ldap-bind with the user used by ALCASAR
$ldapbind = ldap_bind($ldapconn, $f_ldap_identity, $f_ldap_password);
if (!$ldapbind) {
// Test LDAP Version 3
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldapbind = ldap_bind($ldapconn, $f_ldap_identity, $f_ldap_password);
if (!$ldapbind) {
// LDAP Bind failed
return 0;
}
}
// if ok, try to query the directory of users
$query = $f_ldap_uid.'=*';
$ldap_result = ldap_search($ldapconn, $f_ldap_basedn, $query);
if ($ldap_result) {
$ldap_users_count = ldap_count_entries($ldapconn, $ldap_result);
return ($ldap_users_count + 2);
} else {
return 1;
}
ldap_unbind($ldapconn);
}
$messages = '';
if (isset($_POST['auth_enable'])) {
if ($_POST['auth_enable'] === '1') {
$varErrors = [];
if (isset($_POST['ldap_server'])) $ldap_server = $_POST['ldap_server']; else array_push($varErrors, 'Variable error "ldap_server"');
if (isset($_POST['ldap_base_dn'])) $ldap_base_dn = $_POST['ldap_base_dn']; else array_push($varErrors, 'Variable error "ldap_base_dn"');
if (isset($_POST['ldap_uid'])) $ldap_uid = $_POST['ldap_uid']; else array_push($varErrors, 'Variable error "ldap_uid"');
if (isset($_POST['ldap_base_filter'])) $ldap_base_filter = $_POST['ldap_base_filter']; else array_push($varErrors, 'Variable error "ldap_base_filter"');
if (isset($_POST['ldap_user'])) $ldap_user = $_POST['ldap_user']; else array_push($varErrors, 'Variable error "ldap_user"');
if (isset($_POST['ldap_password'])) $ldap_password = $_POST['ldap_password']; else array_push($varErrors, 'Variable error "ldap_password"');
// Validation
if (isset($ldap_server)) {
if ((!preg_match('/^([0-9]{1,3}\.){3}([0-9]{1,3})$/', $ldap_server)) && (preg_match('/^[a-zA-Z0-9-_.]+$/', $ldap_server))) {
$ldap_server = gethostbyname($ldap_server);
}
if (!preg_match('/^([0-9]{1,3}\.){3}([0-9]{1,3})$/', $ldap_server)) {
array_push($varErrors, 'Invalid LDAP server IP');
}
}
if (!empty($varErrors)) {
foreach ($varErrors as $error) {
$messages .= '<span style="font-weight: bold; color: red;">'.$error.'</span><br>';
}
} else {
exec('sed -i '.escapeshellarg("s/^LDAP_SERVER=.*/LDAP_SERVER=$ldap_server/g").' '.CONF_FILE);
exec('sed -i '.escapeshellarg("s/^LDAP_BASE=.*/LDAP_BASE=$ldap_base_dn/g").' '.CONF_FILE);
exec('sed -i '.escapeshellarg("s/^LDAP_UID=.*/LDAP_UID=$ldap_uid/g").' '.CONF_FILE);
exec('sed -i '.escapeshellarg("s/^LDAP_FILTER=.*/LDAP_FILTER=$ldap_base_filter/g").' '.CONF_FILE);
exec('sed -i '.escapeshellarg("s/^LDAP_USER=.*/LDAP_USER=$ldap_user/g").' '.CONF_FILE);
exec('sed -i '.escapeshellarg("s/^LDAP_PASSWORD=.*/LDAP_PASSWORD=$ldap_password/g").' '.CONF_FILE);
exec('sed -i \'s/^LDAP=.*/LDAP=on/g\' '.CONF_FILE);
exec('sudo /usr/local/bin/alcasar-ldap.sh --on');
$messages .= '<span style="font-weight: bold; color: green;">'.$l_ldap_update.'</span><br>';
}
} else {
exec('sed -i "s/^LDAP=.*/LDAP=off/g" '.CONF_FILE);
exec('sudo /usr/local/bin/alcasar-ldap.sh --off');
$messages .= '<span style="font-weight: bold; color: green;">'.$l_ldap_update.'</span><br>';
}
// Reload configuration
$file_conf = fopen(CONF_FILE, 'r');
if (!$file_conf) {
exit('Error opening the file '.CONF_FILE);
}
while (!feof($file_conf)) {
$buffer = fgets($file_conf, 4096);
if ((strpos($buffer, '=') !== false) && (substr($buffer, 0, 1) !== '#')) {
$tmp = explode('=', $buffer, 2);
$conf[trim($tmp[0])] = trim($tmp[1]);
}
}
fclose($file_conf);
}
// LDAP configuration params
$ldap_status = ($conf['LDAP'] === 'on');
$ldap_server = $conf['LDAP_SERVER'];
$ldap_user = $conf['LDAP_USER'];
$ldap_password = $conf['LDAP_PASSWORD'];
$ldap_base_dn = $conf['LDAP_BASE'];
$ldap_uid = $conf['LDAP_UID'];
$ldap_base_filter = $conf['LDAP_FILTER'];
// AJAX LDAP configuration checker
if (isset($_GET['conf_check'])) {
$response = [
'enable' => $ldap_status
];
if ($ldap_status || ($_SERVER['REQUEST_METHOD'] === 'POST')) {
$varErrors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['ldap_server'])) $ldap_server = $_POST['ldap_server']; else array_push($varErrors, 'Variable error "ldap_server"'); // TODO: need to translate
if (isset($_POST['ldap_base_dn'])) $ldap_base_dn = $_POST['ldap_base_dn']; else array_push($varErrors, 'Variable error "ldap_base_dn"'); // TODO: need to translate
if (isset($_POST['ldap_uid'])) $ldap_uid = $_POST['ldap_uid']; else array_push($varErrors, 'Variable error "ldap_uid"'); // TODO: need to translate
if (isset($_POST['ldap_base_filter'])) $ldap_base_filter = $_POST['ldap_base_filter']; else array_push($varErrors, 'Variable error "ldap_base_filter"'); // TODO: need to translate
if (isset($_POST['ldap_user'])) $ldap_user = $_POST['ldap_user']; else array_push($varErrors, 'Variable error "ldap_user"'); // TODO: need to translate
if (isset($_POST['ldap_password'])) $ldap_password = $_POST['ldap_password']; else array_push($varErrors, 'Variable error "ldap_password"'); // TODO: need to translate
}
// Validation
if (isset($ldap_server)) {
if ((!preg_match('/^([0-9]{1,3}\.){3}([0-9]{1,3})$/', $ldap_server)) && (preg_match('/^[a-zA-Z0-9-_.]+$/', $ldap_server))) {
$ldap_server = gethostbyname($ldap_server);
}
if (!preg_match('/^([0-9]{1,3}\.){3}([0-9]{1,3})$/', $ldap_server)) {
array_push($varErrors, 'Invalid LDAP server IP'); // TODO: need to translate
}
}
if (!empty($varErrors)) {
$response['errors'] = $varErrors;
} else {
$response['result'] = ldap_checkServerConfig($ldap_server, $ldap_user, $ldap_password, $ldap_base_dn, $ldap_uid);
}
}
header('Content-Type: application/json');
echo json_encode($response);
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?= $l_ldap_title ?></title>
<link type="text/css" href="/css/style.css" rel="stylesheet">
<link type="text/css" href="/css/acc.css" rel="stylesheet">
<link type="text/css" href="/css/ldap.css" rel="stylesheet">
<script>
function onLdapStatusChange() {
var listToDisables = ['ldap_server', 'ldap_dn', 'ldap_uid', 'ldap_base_filter', 'ldap_user', 'ldap_password'];
var formSubmit = document.querySelector('form input[type="submit"]');
var btn_checkConf = document.getElementById('btn-checkconf');
var isChecked = false;
if (document.getElementById('auth_enable').value === '1') {
for (var i=0; i<listToDisables.length; i++) {
document.getElementById(listToDisables[i]).style.backgroundColor = '#ffffff';
document.getElementById(listToDisables[i]).disabled = false;
}
formSubmit.style.display = 'none';
btn_checkConf.style.display = null;
} else {
for (var i=0; i<listToDisables.length; i++) {
document.getElementById(listToDisables[i]).style.backgroundColor = '#c0c0c0';
document.getElementById(listToDisables[i]).disabled = true;
}
formSubmit.style.display = null;
btn_checkConf.style.display = 'none';
}
}
function checkConfig() {
var messagesElem = document.querySelector('fieldset > legend > div');
var formSubmit = document.querySelector('form input[type="submit"]');
var btn_checkConf = document.getElementById('btn-checkconf');
var ldap_config = {
ldap_status: (document.getElementById('auth_enable').value === '1'),
ldap_server: document.getElementById('ldap_server').value,
ldap_user: document.getElementById('ldap_user').value,
ldap_password: document.getElementById('ldap_password').value,
ldap_base_dn: document.getElementById('ldap_dn').value,
ldap_uid: document.getElementById('ldap_uid').value,
ldap_base_filter: document.getElementById('ldap_base_filter').value
};
// Format HTTP POST data
var post_data = Object.keys(ldap_config).map( function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(ldap_config[k]) } ).join('&');
messagesElem.innerHTML = '<?= $l_checkingConf ?>';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
var data = JSON.parse(this.responseText);
var messages = '';
if (typeof data.result !== 'undefined') {
if (data.result === -2) {
messages += "<span style=\"color: red\"><?= $l_ldap_test_service_failed ?></span>";
} else {
messages += "<span style=\"color: green\"><?= $l_ldap_test_service_ok ?></span>";
if (data.result === -1) {
messages += "<br><span style=\"color: red\"><?= $l_ldap_test_connection_failed ?></span>";
} else {
messages += "<br><span style=\"color: green\"><?= $l_ldap_test_connection_ok ?></span>";
if (data.result === 0) {
messages += "<br><span style=\"color: red\"><?= $l_ldap_test_bind_failed ?></span>";
} else {
messages += "<br><span style=\"color: green\"><?= $l_ldap_test_bind_ok ?></span>";
if (data.result === 1) {
messages += "<br><span style=\"color: red\"><?= $l_ldap_test_dn_failed ?></span>";
} else {
messages += "<br><span style=\"color: green\"><?= $l_ldap_test_dn_ok ?> (" + (data.result - 2) + " <?= $l_ldap_entries?>)</span>";
}
}
}
}
}
if (data.result > 1) {
formSubmit.style.display = null;
btn_checkConf.style.display = 'none';
} else {
formSubmit.style.display = 'none';
btn_checkConf.style.display = null;
}
if (typeof data.errors !== 'undefined') {
messages = '<span style=\"color: red\">' + data.errors.join('</span><br><span style=\"color: red\">') + '</span><br>';
}
messagesElem.innerHTML = messages;
} else {
messagesElem.innerHTML = 'server error';
}
}
};
xhr.open('POST', 'ldap.php?conf_check', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(post_data);
}
</script>
</head>
<body onLoad="onLdapStatusChange();">
<div class="panel">
<div class="panel-header"><?= $l_ldap_legend ?></div>
<div class="panel-body">
<form name="config_ldap" method="POST" action="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<fieldset>
<legend>
<br>
<div style="text-align: center">
<?php if ($messages): ?>
<?= $messages ?>
<?php endif; ?>
</div>
</legend>
<dl>
<dt>
<label for="auth_enable"><?= $l_ldap_auth_enable_label ?></label>
</dt>
<dd>
<select id="auth_enable" name="auth_enable" onchange="onLdapStatusChange();">
<option value="1"<?= ($ldap_status) ? ' selected="selected"' : '' ?>><?= $l_ldap_YES ?></option>
<option value="0"<?= (!$ldap_status) ? ' selected="selected"' : '' ?>><?= $l_ldap_NO ?></option>
</select>
</dd>
</dl>
<dl>
<dt>
<label for="ldap_server"><?= $l_ldap_server_label ?></label><br>
<?= $l_ldap_server_text ?>
</dt>
<dd>
<input type="text" id="ldap_server" size="40" name="ldap_server" value="<?= htmlspecialchars($ldap_server) ?>" oninput="onLdapStatusChange();">
</dd>
</dl>
<dl>
<dt>
<label for="ldap_dn"><?= $l_ldap_base_dn_label ?></label><br>
<?= $l_ldap_base_dn_text ?>
</dt>
<dd>
<input type="text" id="ldap_dn" size="40" name="ldap_base_dn" value="<?= htmlspecialchars($ldap_base_dn) ?>" oninput="onLdapStatusChange();">
</dd>
</dl>
<dl>
<dt>
<label for="ldap_uid"><?= $l_ldap_uid_label ?></label><br>
<?= $l_ldap_uid_text ?>
</dt>
<dd>
<input type="text" id="ldap_uid" size="40" name="ldap_uid" value="<?= htmlspecialchars($ldap_uid) ?>" oninput="onLdapStatusChange();">
</dd>
</dl>
<dl>
<dt>
<label for="ldap_base_filter"><?= $l_ldap_base_filter_label ?></label><br>
<?= $l_ldap_base_filter_text ?>
</dt>
<dd>
<input type="text" id="ldap_base_filter" size="40" name="ldap_base_filter" value="<?= htmlspecialchars($ldap_base_filter) ?>" oninput="onLdapStatusChange();">
</dd>
</dl>
<dl>
<dt>
<label for="ldap_user"><?= $l_ldap_user_label ?></label><br>
<?= $l_ldap_user_text ?>
</dt>
<dd>
<input type="text" id="ldap_user" size="40" name="ldap_user" value="<?= htmlspecialchars($ldap_user) ?>" oninput="onLdapStatusChange();">
</dd>
</dl>
<dl>
<dt>
<label for="ldap_password"><?= $l_ldap_password_label ?></label><br>
<?= $l_ldap_password_text ?>
</dt>
<dd>
<input type="text" id="ldap_password" type="password" size="40" name="ldap_password" value="<?= htmlspecialchars($ldap_password) ?>" oninput="onLdapStatusChange();">
</dd>
</dl>
<p>
<button id="btn-checkconf" onclick="checkConfig(); return false;"><?= $l_check ?></button>
<input id="submit" type="submit" value="<?= $l_ldap_submit ?>" name="submit">
</p>
</fieldset>
</form>
</div>
</div>
</body>
</html>