· 5 years ago · May 12, 2020, 12:54 AM
1<?php
2/*
3 *********************************************************************
4 * LogAnalyzer - http://loganalyzer.adiscon.com
5 * ----------------------------------------------------------------- *
6 * UserDB needed functions *
7 * *
8 * -> *
9 * *
10 * All directives are explained within this file *
11 *
12 * Copyright (C) 2008-2010 Adiscon GmbH.
13 *
14 * This file is part of LogAnalyzer.
15 *
16 * LogAnalyzer is free software: you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation, either version 3 of the License, or
19 * (at your option) any later version.
20 *
21 * LogAnalyzer is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with LogAnalyzer. If not, see <http://www.gnu.org/licenses/>.
28 *
29 * A copy of the GPL can be found in the file "COPYING" in this
30 * distribution.
31 *
32 * Adiscon LogAnalyzer is also available under a commercial license.
33 * For details, contact info@adiscon.com or visit
34 * http://loganalyzer.adiscon.com/commercial
35 *********************************************************************
36*/
37
38// --- Avoid directly accessing this file!
39if ( !defined('IN_PHPLOGCON') )
40{
41 die('Hacking attempt');
42 exit;
43}
44// ---
45
46// --- Basic Includes
47//include($gl_root_path . 'include/constants_general.php');
48///include($gl_root_path . 'include/constants_logstream.php');
49// ---
50
51// --- Define User System initialized!
52define('IS_USERSYSTEMENABLED', true);
53$content['IS_USERSYSTEMENABLED'] = true;
54// ---
55
56// --- BEGIN Usermanagement Function ---
57function InitUserSession()
58{
59 global $USERCFG, $content;
60
61 // --- Hide donate Button if not on Admin Page
62 if ( !defined('IS_ADMINPAGE') )
63 $content['SHOW_DONATEBUTTON'] = false;
64 // ---
65
66 if ( isset($_SESSION['SESSION_LOGGEDIN']) )
67 {
68 if ( !$_SESSION['SESSION_LOGGEDIN'] ||
69 !isset($_SESSION['SESSION_USERID']) /* Check if UserID is set! */
70 )
71 {
72 $content['SESSION_LOGGEDIN'] = false;
73
74 // Not logged in
75 return false;
76 }
77 else
78 {
79 // Copy variables from session!
80 $content['SESSION_LOGGEDIN'] = true;
81 $content['SESSION_USERNAME'] = $_SESSION['SESSION_USERNAME'];
82 $content['SESSION_USERID'] = $_SESSION['SESSION_USERID'];
83 $content['SESSION_ISADMIN'] = $_SESSION['SESSION_ISADMIN'];
84 $content['SESSION_ISREADONLY'] = $_SESSION['SESSION_ISREADONLY'];
85 if ( isset($_SESSION['SESSION_GROUPIDS']) )
86 $content['SESSION_GROUPIDS'] = $_SESSION['SESSION_GROUPIDS'];
87
88 // Set some variable defaults here
89 $content['SHOW_ADMINPANEL'] = "true";
90
91 // --- Now we obtain user specific general settings from the DB for the user!
92 $result = DB_Query("SELECT * FROM `" . DB_CONFIG . "` WHERE userid = " . $content['SESSION_USERID']);
93 if ( $result )
94 {
95 $rows = DB_GetAllRows($result, true);
96 // Read results from DB and overwrite in $CFG Array!
97 if ( isset($rows ) )
98 {
99 for($i = 0; $i < count($rows); $i++)
100 {
101 // Store and overwrite settings from the user here!
102 $USERCFG[ $rows[$i]['propname'] ] = $rows[$i]['propvalue'];
103// $content[ $rows[$i]['propname'] ] = $rows[$i]['propvalue'];
104 }
105 }
106 }
107 else // Critical ERROR HERE!
108 DieWithFriendlyErrorMsg( "Critical Error occured while trying to access the database in table '" . DB_CONFIG . "'" );
109 // ---
110
111 if ( isset($_SESSION['UPDATEAVAILABLE']) && $_SESSION['UPDATEAVAILABLE'] )
112 {
113 // Check Version numbers again to avoid update notification if update was done during meantime!
114 if ( CompareVersionNumbers($content['BUILDNUMBER'], $_SESSION['UPDATEVERSION']) )
115 {
116 $content['UPDATEVERSION'] = $_SESSION['UPDATEVERSION'];
117 $content['isupdateavailable'] = true;
118 $content['isupdateavailable_updatelink'] = $_SESSION['UPDATELINK'];
119 $content['UPDATE_AVAILABLETEXT'] = GetAndReplaceLangStr($content['LN_UPDATE_AVAILABLETEXT'], $content['BUILDNUMBER'], $_SESSION['UPDATEVERSION']);
120 }
121 }
122
123 // --- Extracheck for available database updates!
124 if ( isset($content['database_forcedatabaseupdate']) && $content['database_forcedatabaseupdate'] == "yes" && !defined('IS_UPRGADEPAGE') )
125 RedirectToDatabaseUpgrade();
126 // ---
127
128 // Successfully logged in
129 return true;
130 }
131 }
132 else
133 {
134 $content['SESSION_LOGGEDIN'] = false;
135
136 // Not logged in ^^
137 return false;
138 }
139}
140
141function CreateUserName( $username, $password, $is_admin )
142{
143 /* DB_RemoveBadChars() needs to be done here to maintain backwards compatibility even if it is not needed here*/
144 $md5pass = md5(DB_RemoveBadChars($password));
145 $result = DB_Query("SELECT username FROM `" . DB_USERS . "` WHERE username = '" . $username . "'");
146 $rows = DB_GetAllRows($result, true);
147
148 if ( isset($rows) )
149 {
150 DieWithFriendlyErrorMsg( "User $username already exists!" );
151
152 // User not created!
153 return false;
154 }
155 else
156 {
157 // Create User
158 $result = DB_Query("INSERT INTO `" . DB_USERS . "` (username, password, is_admin) VALUES ('$username', '$md5pass', $is_admin)");
159 DB_FreeQuery($result);
160
161 // Success
162 return true;
163 }
164}
165
166function CheckUserLogin( $username, $password )
167{
168 global $content;
169
170 // Check if LDAP Auth has to be used!
171 if ( GetConfigSetting("UserDBAuthMode", USERDB_AUTH_INTERNAL) == USERDB_AUTH_LDAP)
172 {
173 // perform user auth using LDAP, will add user record to loganalyzer DB if necessary
174 $myrow = CheckLDAPUserLogin( $username, $password );
175 }
176 else // Normal MYSQL Login!
177 {
178 // TODO: SessionTime and AccessLevel check
179 $md5pass = md5(DB_RemoveBadChars($password)); /* DB_RemoveBadChars() needs to be done here to maintain backwards compatibility even if it is not needed here*/
180 $sqlquery = "SELECT * FROM `" . DB_USERS . "` WHERE username = '" . $username . "' and password = '" . $md5pass . "'";
181 $result = DB_Query($sqlquery);
182 $myrow = DB_GetSingleRow($result, true);
183 }
184
185 // The admin field must be set!
186 if ( isset($myrow['is_admin']) )
187 {
188 $_SESSION['SESSION_LOGGEDIN'] = true;
189 $_SESSION['SESSION_USERNAME'] = $username;
190 $_SESSION['SESSION_USERID'] = $myrow['ID'];
191 $_SESSION['SESSION_ISADMIN'] = $myrow['is_admin'];
192 // Check Readonly setting
193 if ( $content['database_installedversion'] > 8 )
194 $_SESSION['SESSION_ISREADONLY'] = $myrow['is_readonly'];
195 else
196 $_SESSION['SESSION_ISREADONLY'] = false;
197
198 $content['SESSION_LOGGEDIN'] = $_SESSION['SESSION_LOGGEDIN'];
199 $content['SESSION_USERNAME'] = $_SESSION['SESSION_USERNAME'];
200 $content['SESSION_USERID'] = $_SESSION['SESSION_USERID'];
201 $content['SESSION_ISADMIN'] = $_SESSION['SESSION_ISADMIN'];
202 $content['SESSION_ISREADONLY'] = $_SESSION['SESSION_ISREADONLY'];
203
204 // --- Read Groupmember ship for the user!
205 $sqlquery = "SELECT " .
206 DB_GROUPMEMBERS . ".groupid, " .
207 DB_GROUPMEMBERS . ".is_member " .
208 "FROM `" . DB_GROUPMEMBERS . "` WHERE userid = " . $content['SESSION_USERID'] . " AND `" . DB_GROUPMEMBERS . "`.is_member = 1";
209 $result = DB_Query($sqlquery);
210 $myrows = DB_GetAllRows($result, true);
211 if ( isset($myrows ) && count($myrows) > 0 )
212 {
213 for($i = 0; $i < count($myrows); $i++)
214 {
215 if ( isset($content['SESSION_GROUPIDS']) )
216 $content['SESSION_GROUPIDS'] .= ", " . $myrows[$i]['groupid'];
217 else
218 $content['SESSION_GROUPIDS'] = $myrows[$i]['groupid'];
219 }
220 }
221
222 // Copy into session as well
223 $_SESSION['SESSION_GROUPIDS'] = $content['SESSION_GROUPIDS'];
224 // ---
225
226 // ---Set LASTLOGIN Time!
227 $result = DB_Query("UPDATE `" . DB_USERS . "` SET last_login = " . time() . " WHERE ID = " . $content['SESSION_USERID']);
228 DB_FreeQuery($result);
229 // ---
230
231 // --- Extracheck for available database updates!
232 if ( isset($content['database_forcedatabaseupdate']) && $content['database_forcedatabaseupdate'] == "yes" && !defined('IS_UPRGADEPAGE') )
233 RedirectToDatabaseUpgrade();
234 // ---
235
236 // --- Now we check for an PhpLogCon Update
237 $iProxyLen = strlen(GetConfigSetting("UseProxyServerForRemoteQueries", ""));
238 if ( $iProxyLen > 0 )
239 {
240 // Proxy Server configured, create a context with proxy option!
241 $opts = array('http' => array('proxy' => 'tcp://' . GetConfigSetting("UseProxyServerForRemoteQueries", ""), 'request_fulluri' => true));
242 $context = stream_context_create($opts);
243
244 // Create handle with my context!
245 $myHandle = @fopen($content['UPDATEURL'], "r", false, $context);
246 }
247 else
248 $myHandle = @fopen($content['UPDATEURL'], "r");
249
250 if( $myHandle )
251 {
252 $myBuffer = "";
253 while (!feof ($myHandle))
254 $myBuffer .= fgets($myHandle, 4096);
255 fclose($myHandle);
256
257 $myLines = explode("\n", $myBuffer);
258
259 // Compare Version numbers!
260 if ( CompareVersionNumbers($content['BUILDNUMBER'], $myLines[0]) )
261 {
262 // True means new version available!
263 $_SESSION['UPDATEAVAILABLE'] = true;
264 $_SESSION['UPDATEVERSION'] = $myLines[0];
265 if ( isset($myLines[1]) )
266 $_SESSION['UPDATELINK'] = $myLines[1];
267 else
268 $_SESSION['UPDATELINK'] = "http://www.phplogcon.org";
269 }
270 }
271 // ---
272
273 // Success !
274 return true;
275 }
276 else
277 {
278 /*
279 if (isset($myrow) && is_numeric($myrow) )
280 {
281 //return error code!
282 return $myrow;
283 }
284 */
285 if ( GetConfigSetting("DebugUserLogin", 0) == 1 )
286 DieWithFriendlyErrorMsg( "Debug Error: Could not find user '" . $username . "' <br><br><B>Sessionarray</B> <pre>" . var_export($_SESSION, true) . "</pre>");
287
288 // Default return false
289 return false;
290 }
291}
292
293function DoLDAPConnect()
294{
295 global $content;
296
297 // Open LDAP connection
298 if (!($ldapConn=@ldap_connect($content['LDAPServer'],$content['LDAPPort'])))
299 return false;
300
301 ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
302
303 // reached this point means success!
304 return $ldapConn;
305}
306
307function DoLDAPBind($ldapConn)
308{
309 global $content;
310
311 // Bind as the privilegied user
312 return ldap_bind($ldapConn, $content['LDAPBindDN'], $content['LDAPBindPassword']);
313}
314
315function CheckLDAPUserLogin( $username, $password )
316{
317 global $content;
318
319 // Create LDAP Searchfilter
320 $ldap_filter='(&'.$content['LDAPSearchFilter'].'('.$content['LDAPUidAttribute'].'='.$username.'))';
321
322 // Get LDAP Connection
323 $ldapConn = DoLDAPConnect();
324 if ( $ldapConn )
325 {
326 if ( !DoLDAPBind($ldapConn) )
327 {
328 if ( GetConfigSetting("DebugUserLogin", 0) == 1 )
329 {
330 // Die with error
331 DebugLDAPErrorAndDie( GetAndReplaceLangStr($content['LN_LOGIN_LDAP_USERBINDFAILED'], $content['LDAPBindDN'], ldap_err2str(ldap_errno($ldapConn))), $ldap_filter );
332 }
333
334 return false;
335 }
336 }
337 else
338 {
339 if ( GetConfigSetting("DebugUserLogin", 0) == 1 )
340 {
341 // Die with error
342 DebugLDAPErrorAndDie( GetAndReplaceLangStr($content['LN_LOGIN_LDAP_SERVERFAILED'], $content['LDAPServer'] . ":" . $content['LDAPPort'], ldap_err2str(ldap_errno($ldapConn))), $ldap_filter );
343 }
344
345 // return false in this case
346 return false;
347 }
348
349 // Search for the user
350 if (!($r=@ldap_search( $ldapConn, $content['LDAPBaseDN'], $ldap_filter, array("uid","cn","localentryid","userpassword") )))
351 {
352 if ( GetConfigSetting("DebugUserLogin", 0) == 1 )
353 {
354 // Die with error
355 DebugLDAPErrorAndDie( GetAndReplaceLangStr($content['LN_LOGIN_LDAP_USERCOULDNOTLOGIN'], $username, ldap_err2str(ldap_errno($ldapConn))), $ldap_filter );
356 }
357
358 // return false in this case
359 return false;
360 }
361
362 $info = ldap_get_entries($ldapConn, $r);
363 if (!$info || $info["count"] != 1)
364 {
365 if ( GetConfigSetting("DebugUserLogin", 0) == 1 )
366 {
367 // Die with error
368 DebugLDAPErrorAndDie( GetAndReplaceLangStr( $content['LN_LOGIN_LDAP_USERNOTFOUND'], $username ), $ldap_filter );
369 }
370
371 // return false in this case
372 return false;
373 }
374
375 // now we have the user data. Do a bind to check for his password
376 if (!($r=@ldap_bind( $ldapConn, $info[0]['dn'],$password)))
377 {
378 if ( GetConfigSetting("DebugUserLogin", 0) == 1 )
379 {
380 // Die with error
381 DebugLDAPErrorAndDie( GetAndReplaceLangStr( $content['LN_LOGIN_LDAP_PASSWORDFAIL'], $username ), $ldap_filter );
382 }
383
384 // return false in this case
385 return false;
386 }
387
388 // for the moment when a user logs in from LDAP, create it in the DB.
389 // then the prefs and group management is done in the DB and we don't rewrite the whole Loganalyzer code�
390
391 /* DB_RemoveBadChars() needs to be done here to maintain backwards compatibility even if it is not needed here*/
392 $md5pass = md5(DB_RemoveBadChars($password));
393
394 // check if the user already exist
395 $sqlquery = "SELECT * FROM `" . DB_USERS . "` WHERE username = '" . $username . "'";
396 $result = DB_Query($sqlquery);
397 $myrow = DB_GetSingleRow($result, true);
398 if (!isset($myrow['is_admin']) )
399 {
400 // Create User | use password to create MD5 Hash, so technically the user could login without LDAP as well
401 $sqlcmd = "INSERT INTO `" . DB_USERS . "` (username, password, is_admin, is_readonly) VALUES ('" . $username . "', '" . $md5pass . "', 0, 1)";
402
403 $result = DB_Query($sqlcmd);
404 DB_FreeQuery($result);
405 $myrow['is_admin'] = 0;
406 $myrow['last_login'] = 0;
407 $myrow['is_readonly'] = 1;
408 }
409
410 // Construct Row and return
411 $myrowfinal['username'] = $username;
412 $myrowfinal['password'] = $md5pass;
413 $myrowfinal['dn'] = $info[0]['dn'];
414 if ( isset($myrow['ID']) )
415 $myrowfinal['ID'] = $myrow['ID']; // Get from SELECT
416 else
417 $myrowfinal['ID'] = DB_ReturnLastInsertID(); // Get from last insert!
418 $myrowfinal['is_admin'] = $myrow['is_admin'];
419 $myrowfinal['is_readonly'] = $myrow['is_readonly'];
420 $myrowfinal['last_login'] = $myrow['last_login'];
421 return $myrowfinal;
422
423}
424
425/*
426* LDAP Debug Helpre function
427*/
428function DebugLDAPErrorAndDie($szErrorMsg, $szLdapFilter)
429{
430 global $content;
431
432 // Add extra debug if wanted!
433 if ( GetConfigSetting("MiscShowDebugMsg", 0, CFGLEVEL_USER) == 1 )
434 {
435 $szErrorMsg .=
436 "</br></br>LDAPBind DN: " . $content['LDAPBindDN'] .
437 "</br>Search Filter: " . $szLdapFilter .
438 "</br><pre>Session Array: </br>" . var_export($_SESSION, true) . "</pre>";
439 }
440
441 // USER NOT FOUND
442 DieWithFriendlyErrorMsg( $szErrorMsg );
443}
444
445
446function DoLogOff()
447{
448 global $content;
449
450 unset( $_SESSION['SESSION_LOGGEDIN'] );
451 unset( $_SESSION['SESSION_USERNAME'] );
452 unset( $_SESSION['SESSION_USERID'] );
453 unset( $_SESSION['SESSION_ACCESSLEVEL'] );
454
455 // Redir to Index Page
456 RedirectPage( "index.php");
457}
458
459function RedirectToUserLogin()
460{
461 global $content;
462
463 // build referer
464 $referer = $_SERVER['PHP_SELF'];
465 if ( isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0 )
466 $referer .= "?" . $_SERVER['QUERY_STRING'];
467 $referer = SecureRedirect($referer);
468
469 header("Location: " . $content['BASEPATH'] . "login.php?referer=" . urlencode($referer) );
470 exit;
471}
472
473function RedirectToDatabaseUpgrade()
474{
475 global $content;
476
477 // build referer
478 $referer = $_SERVER['PHP_SELF'];
479 if ( isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0 )
480 $referer .= "?" . $_SERVER['QUERY_STRING'];
481 $referer = SecureRedirect($referer);
482
483 header("Location: " . $content['BASEPATH'] . "admin/upgrade.php?referer=" . urlencode($referer) );
484 exit;
485}
486// --- END Usermanagement Function ---
487
488
489/*
490* Helper function to obtain a list of groups for display
491*/
492function GetGroupsForSelectfield()
493{
494 global $content;
495
496 $sqlquery = "SELECT " .
497 DB_GROUPS . ".ID as mygroupid, " .
498 DB_GROUPS . ".groupname " .
499 "FROM `" . DB_GROUPS . "`" .
500 " ORDER BY `" . DB_GROUPS . "`.groupname";
501 $result = DB_Query($sqlquery);
502 $mygroups = DB_GetAllRows($result, true);
503 if ( isset($mygroups) && count($mygroups) > 0 )
504 {
505 // Process All Groups
506 for($i = 0; $i < count($mygroups); $i++)
507 $mygroups[$i]['group_selected'] = "";
508
509 // Enable Group Selection
510 array_unshift( $mygroups, array ("mygroupid" => -1, "groupname" => $content['LN_SEARCH_SELGROUPENABLE'], "group_selected" => "") );
511
512 // return result
513 return $mygroups;
514 }
515 else
516 return false;
517 // ---
518}
519
520// Helper function to compare versions
521function CompareVersionNumbers( $oldVer, $newVer )
522{
523 // Split version numbers
524 $currentVersion = explode(".", trim($oldVer) );
525 $newVersion = explode(".", trim($newVer) );
526
527 // Check if the format is correct!
528 if ( count($newVersion) != 3 )
529 return false;
530
531 // check for update
532 if ( isset($newVersion[0]) && $newVersion[0] > $currentVersion[0] )
533 return true;
534 else if ( isset($newVersion[1]) && $newVersion[0] == $currentVersion[0] && $newVersion[1] > $currentVersion[1] )
535 return true;
536 else if ( isset($newVersion[2]) && $newVersion[0] == $currentVersion[0] && $newVersion[1] == $currentVersion[1] && $newVersion[2] > $currentVersion[2] )
537 return true;
538 else
539 return false;
540}
541
542
543
544?>