Project

General

Profile

Download (39.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/* $Id$ */
3
/*
4
	Copyright (C) 2010 Ermal Lu?i
5
	All rights reserved.
6

    
7
	Copyright (C) 2007, 2008 Scott Ullrich <sullrich@gmail.com>
8
	All rights reserved.
9

    
10
        Copyright (C) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
11
        All rights reserved.
12

    
13
        Copyright (C) 2006 Paul Taylor <paultaylor@winn-dixie.com>.
14
        All rights reserved.
15

    
16
        Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
17
        All rights reserved.
18

    
19
        Redistribution and use in source and binary forms, with or without
20
        modification, are permitted provided that the following conditions are met:
21

    
22
        1. Redistributions of source code must retain the above copyright notice,
23
           this list of conditions and the following disclaimer.
24

    
25
        2. Redistributions in binary form must reproduce the above copyright
26
           notice, this list of conditions and the following disclaimer in the
27
           documentation and/or other materials provided with the distribution.
28

    
29
        THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
30
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
31
        AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
32
        AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
33
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36
        CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
        ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38
        POSSIBILITY OF SUCH DAMAGE.
39

    
40
		DISABLE_PHP_LINT_CHECKING
41
		pfSense_BUILDER_BINARIES:	/usr/sbin/pw	/bin/cp
42
		pfSense_MODULE:	auth
43
*/
44

    
45
/*
46
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
47
 * file courtesy of Michael Retterklieber.
48
 */
49
if(!$do_not_include_config_gui_inc)
50
	require_once("config.gui.inc");
51

    
52
// Will be changed to false if security checks fail
53
$security_passed = true;
54

    
55
/* If this function doesn't exist, we're being called from Captive Portal or 
56
   another internal subsystem which does not include authgui.inc */
57
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
58
	/* DNS ReBinding attack prevention.  http://redmine.pfsense.org/issues/708 */
59
	$found_host = false;
60
	if(strstr($_SERVER['HTTP_HOST'], ":")) {
61
		$http_host_port = explode(":", $_SERVER['HTTP_HOST']);
62
		$http_host = $http_host_port[0];
63
	} else {
64
		$http_host = $_SERVER['HTTP_HOST'];
65
	}
66
	if(is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
67
			strcasecmp($http_host, "localhost") == 0)
68
		$found_host = true;
69
	if(strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
70
			strcasecmp($http_host, $config['system']['hostname']) == 0)
71
		$found_host = true;
72

    
73
	if(is_array($config['dyndnses']['dyndns']) && !$found_host)
74
		foreach($config['dyndnses']['dyndns'] as $dyndns)
75
			if(strcasecmp($dyndns['host'], $http_host) == 0) {
76
				$found_host = true;
77
				break;
78
			}
79

    
80
	if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
81
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
82
		foreach ($althosts as $ah)
83
			if(strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
84
				$found_host = true;
85
				break;
86
			}
87
	}
88

    
89
	if($found_host == false) {
90
		if(!security_checks_disabled()) {
91
			display_error_form("501", "Potential DNS Rebind attack detected, see http://en.wikipedia.org/wiki/DNS_rebinding<br/>Try accessing the router by IP address instead of by hostname.");
92
			exit;
93
		}
94
		$security_passed = false;
95
	}
96
}
97

    
98
// If the HTTP_REFERER is something other than ourselves then disallow.
99
if(function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
100
	if($_SERVER['HTTP_REFERER']) {
101
		if(file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
102
			if($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
103
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
104
				header("Refresh: 1; url=index.php");
105
				echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
106
				echo "<html><head><title>" . gettext("Redirecting...") . "</title></head><body>" . gettext("Redirecting to the dashboard...") . "</body></html>";
107
				exit;
108
			}
109
		}
110
		$found_host = false;
111
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
112
		if($referrer_host) {
113
			if(strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0
114
					|| strcasecmp($referrer_host, $config['system']['hostname']) == 0)
115
				$found_host = true;
116
			if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
117
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
118
				foreach ($althosts as $ah) {
119
					if(strcasecmp($referrer_host, $ah) == 0) {
120
						$found_host = true;
121
						break;
122
					}
123
				}
124
			}
125
			if(!$found_host) {
126
				$interface_list_ips = get_configured_ip_addresses();
127
				foreach($interface_list_ips as $ilips) {
128
					if(strcasecmp($referrer_host, $ilips) == 0) {
129
						$found_host = true;
130
						break;
131
					}
132
				}
133
				if($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
134
					// allow SSH port forwarded connections and links from localhost
135
					$found_host = true;
136
				}
137
			}
138
		}
139
		if($found_host == false) {
140
			if(!security_checks_disabled()) {
141
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  You can disable this check if needed in System -> Advanced -> Admin.");
142
				exit;
143
			}
144
			$security_passed = false;
145
		}
146
	} else
147
		$security_passed = false;
148
}
149

    
150
if (function_exists("display_error_form") && $security_passed)
151
	/* Security checks passed, so it should be OK to turn them back on */
152
	restore_security_checks();
153
unset($security_passed);
154

    
155
$groupindex = index_groups();
156
$userindex = index_users();
157

    
158
function index_groups() {
159
	global $g, $debug, $config, $groupindex;
160

    
161
	$groupindex = array();
162

    
163
	if (is_array($config['system']['group'])) {
164
		$i = 0;
165
		foreach($config['system']['group'] as $groupent) {
166
			$groupindex[$groupent['name']] = $i;
167
			$i++;
168
		}
169
	}
170

    
171
	return ($groupindex);
172
}
173

    
174
function index_users() {
175
	global $g, $debug, $config;
176

    
177
	if (is_array($config['system']['user'])) {
178
		$i = 0;
179
		foreach($config['system']['user'] as $userent) {
180
			$userindex[$userent['name']] = $i;
181
			$i++;
182
		}
183
	}
184

    
185
	return ($userindex);
186
}
187

    
188
function & getUserEntry($name) {
189
	global $debug, $config, $userindex;
190
	if (isset($userindex[$name]))
191
		return $config['system']['user'][$userindex[$name]];
192
}
193

    
194
function & getUserEntryByUID($uid) {
195
	global $debug, $config;
196

    
197
	if (is_array($config['system']['user']))
198
		foreach ($config['system']['user'] as & $user)
199
			if ($user['uid'] == $uid)
200
				return $user;
201

    
202
	return false;
203
}
204

    
205
function & getGroupEntry($name) {
206
	global $debug, $config, $groupindex;
207
	if (isset($groupindex[$name]))
208
		return $config['system']['group'][$groupindex[$name]];
209
}
210

    
211
function & getGroupEntryByGID($gid) {
212
	global $debug, $config;
213

    
214
	if (is_array($config['system']['group']))
215
		foreach ($config['system']['group'] as & $group)
216
			if ($group['gid'] == $gid)
217
				return $group;
218

    
219
	return false;
220
}
221

    
222
function get_user_privileges(& $user) {
223

    
224
        $privs = $user['priv'];
225
        if (!is_array($privs))
226
                $privs = array();
227

    
228
        $names = local_user_get_groups($user, true);
229

    
230
        foreach ($names as $name) {
231
                $group = getGroupEntry($name);
232
                if (is_array($group['priv']))
233
                        $privs = array_merge( $privs, $group['priv']);
234
        }
235

    
236
        return $privs;
237
}
238

    
239
function userHasPrivilege($userent, $privid = false) {
240

    
241
        if (!$privid || !is_array($userent))
242
                return false;
243

    
244
        $privs = get_user_privileges($userent);
245

    
246
        if (!is_array($privs))
247
                return false;
248

    
249
        if (!in_array($privid, $privs))
250
                return false;
251

    
252
        return true;
253
}
254

    
255
function local_backed($username, $passwd) {
256

    
257
	$user = getUserEntry($username);
258
	if (!$user)
259
		return false;
260

    
261
	if (is_account_disabled($username) || is_account_expired($username))
262
		return false;
263

    
264
	if ($user['password'])
265
	{
266
		$passwd = crypt($passwd, $user['password']);
267
		if ($passwd == $user['password'])
268
			return true;
269
	}
270

    
271
	if ($user['md5-hash'])
272
	{
273
		$passwd = md5($passwd);
274
		if ($passwd == $user['md5-hash'])
275
			return true;
276
	}
277

    
278
	return false;
279
}
280

    
281
function local_sync_accounts() {
282
	global $debug, $config;
283
	conf_mount_rw();
284

    
285
	/* remove local users to avoid uid conflicts */
286
	$fd = popen("/usr/sbin/pw usershow -a", "r");
287
	if ($fd) {
288
		while (!feof($fd)) {
289
			$line = explode(":",fgets($fd));
290
			if (((!strncmp($line[0], "_", 1)) || ($line[2] < 2000) || ($line[2] > 65000)) && ($line[0] != "admin"))
291
				continue;
292
			$cmd = "/usr/sbin/pw userdel -n '{$line[0]}'";
293
			if($debug)
294
				log_error("Running: {$cmd}");
295
			mwexec($cmd);
296
		}
297
		pclose($fd);
298
	}
299

    
300
	/* remove local groups to avoid gid conflicts */
301
	$gids = array();
302
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
303
	if ($fd) {
304
		while (!feof($fd)) {
305
			$line = explode(":",fgets($fd));
306
			if (!strncmp($line[0], "_", 1))
307
				continue;
308
			if ($line[2] < 2000)
309
				continue;
310
			if ($line[2] > 65000)
311
				continue;
312
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
313
			if($debug)
314
				log_error("Running: {$cmd}");
315
			mwexec($cmd);
316
		}
317
		pclose($fd);
318
	}
319

    
320
	/* make sure the all group exists */
321
	$allgrp = getGroupEntryByGID(1998);
322
	local_group_set($allgrp, true);
323

    
324
	/* sync all local users */
325
	if (is_array($config['system']['user']))
326
		foreach ($config['system']['user'] as $user)
327
			local_user_set($user);
328

    
329
	/* sync all local groups */
330
	if (is_array($config['system']['group']))
331
		foreach ($config['system']['group'] as $group)
332
			local_group_set($group);
333

    
334
	conf_mount_ro();
335

    
336
}
337

    
338
function local_user_set(& $user) {
339
	global $g, $debug;
340

    
341
	if (empty($user['password'])) {
342
		log_error("There is something wrong in your config because user {$user['name']} password is missing!");
343
		return;
344
	}
345

    
346
	conf_mount_rw();
347

    
348
	$home_base = "/home/";	
349
	$user_uid = $user['uid'];
350
	$user_name = $user['name'];
351
	$user_home = "{$home_base}{$user_name}";
352
	$user_shell = "/etc/rc.initial";
353
	$user_group = "nobody";
354

    
355
	// Ensure $home_base exists and is writable
356
	if (!is_dir($home_base)) 
357
		mkdir($home_base, 0755);
358

    
359
	$lock_account = false;
360
	/* configure shell type */
361
	/* Cases here should be ordered by most privileged to least privileged. */
362
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
363
		$user_shell = "/bin/tcsh";
364
	} elseif (userHasPrivilege($user, "user-copy-files")) {
365
		$user_shell = "/usr/local/bin/scponly";
366
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
367
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
368
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
369
		$user_shell = "/sbin/nologin";
370
	} else {
371
		$user_shell = "/sbin/nologin";
372
		$lock_account = true;
373
	}
374

    
375
	/* Lock out disabled or expired users, unless it's root/admin. */
376
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
377
		$user_shell = "/sbin/nologin";
378
		$lock_account = true;
379
	}
380

    
381
	/* root user special handling */
382
	if ($user_uid == 0) {
383
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
384
		if($debug)
385
			log_error("Running: {$cmd}");
386
		$fd = popen($cmd, "w");
387
		fwrite($fd, $user['password']);
388
		pclose($fd);
389
		$user_group = "wheel";
390
		$user_home = "/root";
391
		$user_shell = "/etc/rc.initial";
392
	}
393

    
394
	/* read from pw db */
395
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
396
	$pwread = fgets($fd);
397
	pclose($fd);
398
	$userattrs = explode(":", trim($pwread));
399

    
400
	/* determine add or mod */
401
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
402
		$user_op = "useradd -m -k /etc/skel -o";
403
	} else {
404
		$user_op = "usermod";
405
	}
406

    
407
	/* add or mod pw db */
408
	$cmd = "/usr/sbin/pw {$user_op} -q -u {$user_uid} -n {$user_name}".
409
			" -g {$user_group} -s {$user_shell} -d {$user_home}".
410
			" -c ".escapeshellarg($user['descr'])." -H 0 2>&1";
411

    
412
	if($debug)
413
		log_error("Running: {$cmd}");
414
	$fd = popen($cmd, "w");
415
	fwrite($fd, $user['password']);
416
	pclose($fd);
417

    
418
	/* create user directory if required */
419
	if (!is_dir($user_home)) {
420
		mkdir($user_home, 0700);
421
		mwexec("/bin/cp /root/.* {$home_base}/", true);
422
	}
423
	chown($user_home, $user_name);
424
	chgrp($user_home, $user_group);
425

    
426
	/* write out ssh authorized key file */
427
	if($user['authorizedkeys']) {
428
		if (!is_dir("{$user_home}/.ssh")) {
429
			mkdir("{$user_home}/.ssh", 0700);
430
			chown("{$user_home}/.ssh", $user_name);
431
		}
432
		$keys = base64_decode($user['authorizedkeys']);
433
		file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
434
		chown("{$user_home}/.ssh/authorized_keys", $user_name);
435
	} else
436
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
437

    
438
	$un = $lock_account ? "" : "un";
439
	exec("/usr/sbin/pw {$un}lock {$user_name} -q");
440
	
441
	conf_mount_ro();
442
}
443

    
444
function local_user_del($user) {
445
	global $debug;
446

    
447
	/* remove all memberships */
448
	local_user_set_groups($user);
449

    
450
	/* Don't remove /root */
451
	if ($user['uid'] != 0)
452
		$rmhome = "-r";
453

    
454
	/* read from pw db */
455
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
456
	$pwread = fgets($fd);
457
	pclose($fd);
458
	$userattrs = explode(":", trim($pwread));
459

    
460
	if ($userattrs[0] != $user['name']) {
461
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
462
		return;
463
	}
464

    
465
	/* delete from pw db */
466
	$cmd = "/usr/sbin/pw userdel -n {$user['name']} {$rmhome}";
467

    
468
	if($debug)
469
		log_error("Running: {$cmd}");
470
	mwexec($cmd);
471

    
472
	/* Delete user from groups needs a call to write_config() */
473
	local_group_del_user($user);
474
}
475

    
476
function local_user_set_password(& $user, $password) {
477

    
478
	$user['password'] = crypt($password);
479
	$user['md5-hash'] = md5($password);
480

    
481
	// Converts ascii to unicode.
482
	$astr = (string) $password;
483
	$ustr = '';
484
	for ($i = 0; $i < strlen($astr); $i++) {
485
		$a = ord($astr{$i}) << 8;
486
		$ustr.= sprintf("%X", $a);
487
	}
488

    
489
	// Generate the NT-HASH from the unicode string
490
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
491
}
492

    
493
function local_user_get_groups($user, $all = false) {
494
	global $debug, $config;
495

    
496
	$groups = array();
497
	if (!is_array($config['system']['group']))
498
		return $groups;
499

    
500
	foreach ($config['system']['group'] as $group)
501
		if ( $all || ( !$all && ($group['name'] != "all")))
502
			if (is_array($group['member']))
503
				if (in_array($user['uid'], $group['member']))
504
					$groups[] = $group['name'];
505

    
506
	if ( $all )
507
		$groups[] = "all";
508

    
509
	sort($groups);
510

    
511
	return $groups;
512
	
513
}
514

    
515
function local_user_set_groups($user, $new_groups = NULL ) {
516
	global $debug, $config, $groupindex;
517

    
518
	if (!is_array($config['system']['group']))
519
		return;
520

    
521
	$cur_groups = local_user_get_groups($user, true);
522
	$mod_groups = array();
523

    
524
	if (!is_array($new_groups))
525
		$new_groups = array();
526

    
527
	if (!is_array($cur_groups))
528
		$cur_groups = array();
529

    
530
	/* determine which memberships to add */
531
	foreach ($new_groups as $groupname) {
532
		if (in_array($groupname,$cur_groups))
533
			continue;
534
		$group = & $config['system']['group'][$groupindex[$groupname]];
535
		$group['member'][] = $user['uid'];
536
		$mod_groups[] = $group;
537
	}
538
	unset($group);
539

    
540
	/* determine which memberships to remove */
541
	foreach ($cur_groups as $groupname) {
542
		if (in_array($groupname,$new_groups))
543
			continue;
544
		if (!isset($config['system']['group'][$groupindex[$groupname]]))
545
			continue;
546
		$group = & $config['system']['group'][$groupindex[$groupname]];
547
		if (is_array($group['member'])) {
548
			$index = array_search($user['uid'], $group['member']);
549
			array_splice($group['member'], $index, 1);
550
			$mod_groups[] = $group;
551
		}
552
	}
553
	unset($group);
554

    
555
	/* sync all modified groups */
556
	foreach ($mod_groups as $group)
557
		local_group_set($group);
558
}
559

    
560
function local_group_del_user($user) {
561
	global $config;
562

    
563
	if (!is_array($config['system']['group']))
564
                return;
565

    
566
        foreach ($config['system']['group'] as $group) {
567
		if (is_array($group['member'])) {
568
			foreach ($group['member'] as $idx => $uid) {
569
				if ($user['uid'] == $uid)
570
					unset($config['system']['group']['member'][$idx]);
571
			}
572
		}
573
	}
574
}
575

    
576
function local_group_set($group, $reset = false) {
577
	global $debug;
578

    
579
	$group_name = $group['name'];
580
	$group_gid = $group['gid'];
581
	$group_members = "''";
582
	if (!$reset && !empty($group['member']) && count($group['member']) > 0)
583
		$group_members = implode(",",$group['member']);
584

    
585
	/* read from group db */
586
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
587
	$pwread = fgets($fd);
588
	pclose($fd);
589

    
590
	/* determine add or mod */
591
	if (!strncmp($pwread, "pw:", 3))
592
		$group_op = "groupadd";
593
	else
594
		$group_op = "groupmod";
595

    
596
	/* add or mod group db */
597
	$cmd = "/usr/sbin/pw {$group_op} {$group_name} -g {$group_gid} -M {$group_members} 2>&1";
598

    
599
	if($debug)
600
		log_error("Running: {$cmd}");
601
	mwexec($cmd);
602

    
603
}
604

    
605
function local_group_del($group) {
606
	global $debug;
607

    
608
	/* delete from group db */
609
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
610

    
611
	if($debug)
612
		log_error("Running: {$cmd}");
613
	mwexec($cmd);
614
}
615

    
616
function ldap_test_connection($authcfg) {
617
	global $debug, $config, $g;
618

    
619
	if ($authcfg) {
620
                if (strstr($authcfg['ldap_urltype'], "Standard"))
621
                        $ldapproto = "ldap";
622
                else
623
                        $ldapproto = "ldaps";
624
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
625
                $ldapport           = $authcfg['ldap_port'];
626
		if (!empty($ldapport))
627
			$ldapserver .= ":{$ldapport}";
628
                $ldapbasedn         = $authcfg['ldap_basedn'];
629
                $ldapbindun         = $authcfg['ldap_binddn'];
630
                $ldapbindpw         = $authcfg['ldap_bindpw'];
631
        } else
632
		return false;
633

    
634
        /* first check if there is even an LDAP server populated */
635
        if(!$ldapserver)
636
                return false;
637

    
638
        /* Setup CA environment if needed. */
639
        ldap_setup_caenv($authcfg);
640

    
641
        /* connect and see if server is up */
642
        $error = false;
643
	if (!($ldap = ldap_connect($ldapserver)))
644
		$error = true;
645

    
646
        if ($error == true) {
647
                log_error("ERROR!  Could not connect to server {$ldapname}.");
648
                return false;
649
        }
650

    
651
	return true;
652
}
653

    
654
function ldap_setup_caenv($authcfg) {
655
	global $g;
656
	require_once("certs.inc");
657

    
658
	unset($caref);
659
	if (empty($authcfg['ldap_caref']) || !strstr($authcfg['ldap_urltype'], "SSL")) {
660
		putenv('LDAPTLS_REQCERT=never');
661
		return;
662
	} else {
663
		$caref = lookup_ca($authcfg['ldap_caref']);
664
		if (!$caref) {
665
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
666
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
667
			putenv('LDAPTLS_REQCERT=hard');
668
			return;
669
		}
670
		if (!is_dir("{$g['varrun_path']}/certs"))
671
			@mkdir("{$g['varrun_path']}/certs");
672
		if (file_exists("{$g['varrun_path']}/certs/{$authcfg['name']}.ca"))
673
			@unlink("{$g['varrun_path']}/certs/{$authcfg['name']}.ca");
674
		file_put_contents("{$g['varrun_path']}/certs/{$authcfg['name']}.ca", base64_decode($caref['crt']));
675
		@chmod("{$g['varrun_path']}/certs/{$authcfg['name']}.ca", 0600);
676
		putenv('LDAPTLS_REQCERT=hard');
677
		/* XXX: Probably even the hashed link should be created for this? */
678
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
679
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$authcfg['name']}.ca");
680
	}
681
}
682

    
683
function ldap_test_bind($authcfg) {
684
	global $debug, $config, $g;
685

    
686
	if ($authcfg) {
687
                if (strstr($authcfg['ldap_urltype'], "Standard"))
688
                        $ldapproto = "ldap";
689
                else
690
                        $ldapproto = "ldaps";
691
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
692
                $ldapport           = $authcfg['ldap_port'];
693
		if (!empty($ldapport))
694
			$ldapserver .= ":{$ldapport}";
695
                $ldapbasedn         = $authcfg['ldap_basedn'];
696
                $ldapbindun         = $authcfg['ldap_binddn'];
697
                $ldapbindpw         = $authcfg['ldap_bindpw'];
698
                $ldapver            = $authcfg['ldap_protver'];
699
		if (empty($ldapbndun) || empty($ldapbindpw))
700
                        $ldapanon = true;
701
                else
702
                        $ldapanon = false;
703
	} else
704
		return false;
705

    
706
	/* first check if there is even an LDAP server populated */
707
        if(!$ldapserver)
708
                return false;
709

    
710
	/* Setup CA environment if needed. */
711
	ldap_setup_caenv($authcfg);
712

    
713
        /* connect and see if server is up */
714
        $error = false;
715
	if (!($ldap = ldap_connect($ldapserver)))
716
		$error = true;
717

    
718
        if ($error == true) {
719
                log_error("ERROR!  Could not connect to server {$ldapname}.");
720
                return false;
721
        }
722

    
723
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
724
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
725
 
726
	if ($ldapanon == true) {
727
		if (!($res = @ldap_bind($ldap))) {
728
			@ldap_close($ldap);
729
			return false;
730
		}
731
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
732
		@ldap_close($ldap);
733
		return false;
734
	}
735

    
736
	@ldap_unbind($ldap);
737

    
738
	return true;
739
}
740

    
741
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
742
	global $debug, $config, $g;
743

    
744
	if(!function_exists("ldap_connect"))
745
		return;
746

    
747
	$ous = array();
748

    
749
	if ($authcfg) {
750
                if (strstr($authcfg['ldap_urltype'], "Standard"))
751
                        $ldapproto = "ldap";
752
                else
753
                        $ldapproto = "ldaps";
754
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
755
                $ldapport           = $authcfg['ldap_port'];
756
		if (!empty($ldapport))
757
			$ldapserver .= ":{$ldapport}";
758
                $ldapbasedn         = $authcfg['ldap_basedn'];
759
                $ldapbindun         = $authcfg['ldap_binddn'];
760
                $ldapbindpw         = $authcfg['ldap_bindpw'];
761
                $ldapver            = $authcfg['ldap_protver'];
762
		if (empty($ldapbindun) || empty($ldapbindpw))
763
                        $ldapanon = true;
764
                else
765
                        $ldapanon = false;
766
                $ldapname           = $authcfg['name'];
767
                $ldapfallback       = false;
768
		$ldapscope          = $authcfg['ldap_scope'];
769
        } else
770
		return false;
771

    
772
        /* first check if there is even an LDAP server populated */
773
        if(!$ldapserver) {
774
                log_error("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined.");
775
                return $ous;
776
        }
777

    
778
	/* Setup CA environment if needed. */
779
	ldap_setup_caenv($authcfg);
780

    
781
	/* connect and see if server is up */
782
        $error = false;
783
	if (!($ldap = ldap_connect($ldapserver)))
784
		$error = true;
785

    
786
        if ($error == true) {
787
		log_error("ERROR!  Could not connect to server {$ldapname}.");
788
                return $ous;
789
        }
790

    
791
	$ldapfilter = "(|(ou=*)(cn=Users))";
792

    
793
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
794
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
795

    
796
	if ($ldapanon == true) {
797
                if (!($res = @ldap_bind($ldap))) {
798
			log_error("ERROR! ldap_get_user_ous() could not bind anonymously to server {$ldapname}.");
799
			@ldap_close($ldap);
800
                        return $ous;
801
		}
802
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
803
		log_error("ERROR! ldap_get_user_ous() could not bind to server {$ldapname}.");
804
		@ldap_close($ldap);
805
		return $ous;
806
	}
807

    
808
	if ($ldapscope == "one")
809
		$ldapfunc = "ldap_list";
810
	else
811
		$ldapfunc = "ldap_search";
812

    
813
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
814
	$info = @ldap_get_entries($ldap, $search);
815

    
816
	if (is_array($info)) {
817
		foreach ($info as $inf) {
818
			if (!$show_complete_ou) {
819
				$inf_split = split(",", $inf['dn']);
820
				$ou = $inf_split[0];
821
				$ou = str_replace("OU=","", $ou);
822
				$ou = str_replace("CN=","", $ou);
823
			} else
824
				if($inf['dn'])
825
					$ou = $inf['dn'];
826
			if($ou)
827
				$ous[] = $ou;
828
		}
829
	}
830

    
831
	@ldap_unbind($ldap);
832

    
833
	return $ous;
834
}
835

    
836
function ldap_get_groups($username, $authcfg) {
837
	global $debug, $config;
838
	
839
	if(!function_exists("ldap_connect"))
840
		return;
841
	
842
	if(!$username) 
843
		return false;
844

    
845
	if(stristr($username, "@")) {
846
		$username_split=split("\@", $username);
847
		$username = $username_split[0];		
848
	}
849

    
850
	if(stristr($username, "\\")) {
851
		$username_split=split("\\", $username);
852
		$username = $username_split[0];        
853
	}    
854
	
855
	//log_error("Getting LDAP groups for {$username}.");
856
        if ($authcfg) {
857
                if (strstr($authcfg['ldap_urltype'], "Standard"))
858
                        $ldapproto = "ldap";
859
                else
860
                        $ldapproto = "ldaps";
861
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
862
                $ldapport           = $authcfg['ldap_port'];
863
		if (!empty($ldapport))
864
			$ldapserver .= ":{$ldapport}";
865
                $ldapbasedn         = $authcfg['ldap_basedn'];
866
                $ldapbindun         = $authcfg['ldap_binddn'];
867
                $ldapbindpw         = $authcfg['ldap_bindpw'];
868
                $ldapauthcont       = $authcfg['ldap_authcn'];
869
                $ldapnameattribute  = strtolower($authcfg['ldap_attr_user']);
870
                $ldapgroupattribute  = strtolower($authcfg['ldap_attr_member']);
871
                $ldapfilter         = "({$ldapnameattribute}={$username})";
872
                $ldaptype           = "";
873
                $ldapver            = $authcfg['ldap_protver'];
874
		if (empty($ldapbindun) || empty($ldapbindpw))
875
                        $ldapanon = true;
876
                else
877
                        $ldapanon = false;
878
                $ldapname           = $authcfg['name'];
879
                $ldapfallback       = false;
880
		$ldapscope          = $authcfg['ldap_scope'];
881
	} else
882
		return false;
883

    
884
	$ldapdn             = $_SESSION['ldapdn'];
885

    
886
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
887
	$ldapgroupattribute = strtolower($ldapgroupattribute);
888
	$memberof = array();
889

    
890
        /* Setup CA environment if needed. */
891
        ldap_setup_caenv($authcfg);
892

    
893
	/* connect and see if server is up */
894
	$error = false;
895
	if (!($ldap = ldap_connect($ldapserver)))
896
		$error = true;
897

    
898
	if ($error == true) {
899
		log_error("ERROR! ldap_get_groups() Could not connect to server {$ldapname}.");
900
                return memberof;
901
        }
902
    
903
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
904
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
905

    
906
	/* bind as user that has rights to read group attributes */
907
	if ($ldapanon == true) {
908
                if (!($res = @ldap_bind($ldap))) {
909
			log_error("ERROR! ldap_get_groups() could not bind anonymously to server {$ldapname}.");
910
			@ldap_close($ldap);
911
                        return false;
912
		}
913
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
914
		log_error("ERROR! ldap_get_groups() could not bind to server {$ldapname}.");
915
		@ldap_close($ldap);
916
		return memberof;
917
	}
918

    
919
	/* get groups from DN found */
920
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
921
	/* since we know the DN is in $_SESSION['ldapdn'] */
922
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
923
	if ($ldapscope == "one")
924
                $ldapfunc = "ldap_list";
925
        else
926
                $ldapfunc = "ldap_search";
927

    
928
	$search    = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
929
	$info      = @ldap_get_entries($ldap, $search);
930

    
931
	$countem = $info["count"];	
932
	
933
	if(is_array($info[0][$ldapgroupattribute])) {
934
		/* Iterate through the groups and throw them into an array */
935
		foreach ($info[0][$ldapgroupattribute] as $member) {
936
			if (stristr($member, "CN=") !== false) {
937
				$membersplit = split(",", $member);
938
				$memberof[] = preg_replace("/CN=/i", "", $membersplit[0]);
939
			}
940
		}
941
	}
942
	
943
	/* Time to close LDAP connection */
944
	@ldap_unbind($ldap);
945
	
946
	$groups = print_r($memberof,true);
947
	
948
	//log_error("Returning groups ".$groups." for user $username");
949
	
950
	return $memberof;
951
}
952

    
953
function ldap_backed($username, $passwd, $authcfg) {
954
	global $debug, $config;
955
	
956
	if(!$username) 
957
		return;
958

    
959
	if(!function_exists("ldap_connect"))
960
		return;
961

    
962
	if(stristr($username, "@")) {
963
		$username_split=split("\@", $username);
964
		$username = $username_split[0];        
965
	}
966
	if(stristr($username, "\\")) {
967
		$username_split=split("\\", $username);
968
		$username = $username_split[0];        
969
	}
970

    
971
	if ($authcfg) {
972
		if (strstr($authcfg['ldap_urltype'], "Standard"))
973
			$ldapproto = "ldap";
974
		else
975
			$ldapproto = "ldaps";
976
		$ldapserver         = "{$ldapproto}://{$authcfg['host']}";
977
		$ldapport	    = $authcfg['ldap_port'];
978
		if (!empty($ldapport))
979
			$ldapserver .= ":{$ldapport}";
980
                $ldapbasedn         = $authcfg['ldap_basedn'];
981
                $ldapbindun         = $authcfg['ldap_binddn'];
982
                $ldapbindpw         = $authcfg['ldap_bindpw'];
983
		if (empty($ldapbindun) || empty($ldapbindpw))
984
			$ldapanon = true;
985
		else
986
			$ldapanon = false;
987
                $ldapauthcont       = $authcfg['ldap_authcn'];
988
                $ldapnameattribute  = strtolower($authcfg['ldap_attr_user']);
989
                $ldapfilter         = "({$ldapnameattribute}={$username})";
990
                $ldaptype           = "";
991
                $ldapver            = $authcfg['ldap_protver'];
992
		$ldapname	    = $authcfg['name'];
993
		$ldapscope	    = $authcfg['ldap_scope'];
994
	} else
995
		return false;
996

    
997
	/* first check if there is even an LDAP server populated */ 
998
	if(!$ldapserver) {
999
		if ($ldapfallback) {
1000
			log_error("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager.");
1001
			return local_backed($username, $passwd);
1002
		} else
1003
			log_error("ERROR! ldap_backed() called with no LDAP authentication server defined.");
1004

    
1005
		return false;
1006
	}
1007
	
1008
        /* Setup CA environment if needed. */
1009
        ldap_setup_caenv($authcfg);
1010

    
1011
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1012
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1013

    
1014
	/* Make sure we can connect to LDAP */
1015
	$error = false;
1016
	if (!($ldap = ldap_connect($ldapserver)))
1017
		$error = true;
1018

    
1019
	if ($error == true) {
1020
		log_error("ERROR!  Could not connect to server {$ldapname}.");
1021
		return false;
1022
	}
1023

    
1024
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1025
	$error = false;
1026
	if ($ldapanon == true) {
1027
                if (!($res = @ldap_bind($ldap)))
1028
                        $error = true;
1029
	} else if (!($res = ldap_bind($ldap, $ldapbindun, $ldapbindpw)))
1030
		$error = true;
1031

    
1032
	if ($error == true) {
1033
		@ldap_close($ldap);
1034
		log_error("ERROR! Could not bind to server {$ldapname}.");
1035
		return false;
1036
	}
1037
	
1038
	/* Get LDAP Authcontainers and split em up. */
1039
	$ldac_splits = split(";", $ldapauthcont);
1040
	
1041
	/* setup the usercount so we think we havn't found anyone yet */
1042
	$usercount  = 0;
1043

    
1044
	/*****************************************************************/
1045
	/*  We First find the user based on username and filter          */
1046
	/*  Then, once we find the first occurance of that person        */
1047
	/*  We set seesion variables to ponit to the OU and DN of the    */
1048
	/*  Person.  To later be used by ldap_get_groups.                */
1049
	/*  that way we don't have to search twice.                      */
1050
	/*****************************************************************/
1051
	log_error("Now Searching for {$username} in directory.");
1052
	/* Iterate through the user containers for search */
1053
	foreach ($ldac_splits as $i => $ldac_split) {
1054
		/* Make sure we just use the first user we find */
1055
		log_error("Now Searching in server {$ldapname}, container {$ldac_split} with filter {$ldapfilter}.");
1056
		if ($ldapscope == "one")
1057
			$ldapfunc = "ldap_list";
1058
		else
1059
			$ldapfunc = "ldap_search";
1060
		/* Support legacy auth container specification. */
1061
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn))
1062
			$search	 = @$ldapfunc($ldap,$ldac_split,$ldapfilter);
1063
		else
1064
			$search  = @$ldapfunc($ldap,"{$ldac_split},{$ldapbasedn}",$ldapfilter);
1065
		if (!$search) {
1066
			log_error("Search resulted in error: " . ldap_error($ldap));
1067
			continue;
1068
		}
1069
		$info	 = ldap_get_entries($ldap,$search);
1070
		$matches = $info['count'];
1071
		if ($matches == 1){
1072
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1073
			$_SESSION['ldapou'] = $ldac_split[$i];
1074
			$_SESSION['ldapon'] = "true";
1075
			$usercount = 1;
1076
			break;
1077
		}
1078
	}
1079

    
1080
	if ($usercount != 1){
1081
		@ldap_unbind($ldap);
1082
		log_error("ERROR! Either LDAP search failed, or multiple users were found.");
1083
		return false;                         
1084
	}
1085

    
1086
	/* Now lets bind as the user we found */
1087
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1088
		log_error("ERROR! Could not login to server {$ldapname} as user {$username}.");
1089
		@ldap_unbind($ldap);
1090
		return false;
1091
	}
1092

    
1093
	log_error("Logged in successfully as {$username} via LDAP server {$ldapname} with DN = {$userdn}.");
1094

    
1095
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1096
	@ldap_unbind($ldap);
1097

    
1098
	return true;
1099
}
1100

    
1101
function radius_backed($username, $passwd, $authcfg){
1102
	global $debug, $config;
1103
	$ret = false;
1104

    
1105
	require_once("radius.inc");
1106

    
1107
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1108
	if ($authcfg) {
1109
		$radiusservers = array();
1110
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1111
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1112
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1113
	} else
1114
		return false;
1115

    
1116
	/* Add a new servers to our instance */
1117
	foreach ($radiusservers as $radsrv)
1118
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
1119

    
1120
	if (PEAR::isError($rauth->start())) {
1121
		$retvalue['auth_val'] = 1;
1122
		$retvalue['error'] = $rauth->getError();
1123
		if ($debug)
1124
			printf("Radius start: %s<br>\n", $retvalue['error']);
1125
	}
1126

    
1127
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1128

    
1129
	/* Send request */
1130
	$result = $rauth->send();
1131
	if (PEAR::isError($result)) {
1132
		$retvalue['auth_val'] = 1;
1133
		$retvalue['error'] = $result->getMessage();
1134
		if ($debug)
1135
			printf("Radius send failed: %s<br>\n", $retvalue['error']);
1136
	} else if ($result === true) {
1137
		$retvalue['auth_val'] = 2;
1138
		if ($debug)
1139
			printf(gettext("Radius Auth succeeded")."<br>\n");
1140
		$ret = true;
1141
	} else {
1142
		$retvalue['auth_val'] = 3;
1143
		if ($debug)
1144
			printf(gettext("Radius Auth rejected")."<br>\n");
1145
	}
1146

    
1147
	// close OO RADIUS_AUTHENTICATION
1148
	$rauth->close();
1149

    
1150
	return $ret;
1151
}
1152

    
1153
function get_user_expiration_date($username) {
1154
	$user = getUserEntry($username);
1155
	if ($user['expires']) 
1156
		return $user['expires'];
1157
}
1158

    
1159
function is_account_expired($username) {
1160
	$expirydate = get_user_expiration_date($username);
1161
	if ($expirydate) {
1162
		if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($expirydate))))
1163
			return true;
1164
	}
1165

    
1166
	return false;
1167
}
1168

    
1169
function is_account_disabled($username) {
1170
	$user = getUserEntry($username);
1171
	if (isset($user['disabled']))
1172
		return true;
1173

    
1174
	return false;
1175
}
1176

    
1177
function auth_get_authserver($name) {
1178
        global $config;
1179

    
1180
        if (is_array($config['system']['authserver'])) {
1181
                foreach ($config['system']['authserver'] as $authcfg) {
1182
                        if ($authcfg['name'] == $name)
1183
                                return $authcfg;
1184
                }
1185
        }
1186
	if ($name == "Local Database")
1187
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1188
}
1189

    
1190
function auth_get_authserver_list() {
1191
        global $config;
1192

    
1193
	$list = array();
1194

    
1195
        if (is_array($config['system']['authserver'])) {
1196
                foreach ($config['system']['authserver'] as $authcfg) {
1197
			/* Add support for disabled entries? */
1198
			$list[$authcfg['name']] = $authcfg;
1199
                }
1200
        }
1201

    
1202
	$list["Local Database"] = array( "name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1203
	return $list;
1204
}
1205

    
1206
function getUserGroups($username, $authcfg) {
1207
	global $config;
1208

    
1209
	$allowed_groups = array();
1210

    
1211
	switch($authcfg['type']) {
1212
        case 'ldap':
1213
		$allowed_groups = @ldap_get_groups($username, $authcfg);
1214
		break;
1215
	case 'radius':
1216
		break;
1217
	default:
1218
		$user = getUserEntry($username);
1219
		$allowed_groups = @local_user_get_groups($user, true);
1220
		break;
1221
	}
1222

    
1223
	$member_groups = array();
1224
        if (is_array($config['system']['group'])) {
1225
                foreach ($config['system']['group'] as $group)
1226
                        if (in_array($group['name'], $allowed_groups))
1227
				$member_groups[] = $group['name'];
1228
	}
1229

    
1230
	return $member_groups;
1231
}
1232

    
1233
function authenticate_user($username, $password, $authcfg = NULL) {
1234

    
1235
	if (!$authcfg) {
1236
		return local_backed($username, $password);
1237
	}
1238

    
1239
	$authenticated = false;
1240
	switch($authcfg['type']) {
1241
        case 'ldap':
1242
                if (ldap_backed($username, $password, $authcfg))
1243
                        $authenticated = true;
1244
                break;
1245
        case 'radius':
1246
                if (radius_backed($username, $password, $authcfg))
1247
                        $authenticated = true;
1248
                break;
1249
        default:
1250
                /* lookup user object by name */
1251
                if (local_backed($username, $password))
1252
                        $authenticated = true;
1253
                break;
1254
        }
1255

    
1256
	return $authenticated;
1257
}
1258

    
1259
function session_auth() {
1260
	global $HTTP_SERVER_VARS, $config, $_SESSION, $page;
1261

    
1262
	session_start();
1263

    
1264
	/* Validate incoming login request */
1265
	if (isset($_POST['login'])) {
1266
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1267
		if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) || 
1268
		    authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1269
			$_SESSION['Logged_In'] = "True";
1270
			$_SESSION['Username'] = $_POST['usernamefld'];
1271
			$_SESSION['last_access'] = time();
1272
			if(! isset($config['system']['webgui']['quietlogin'])) {
1273
				log_auth("Successful webConfigurator login for user '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1274
			}
1275
			$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1276
			if (isset($_POST['postafterlogin']))
1277
				return true;
1278
			else {
1279
				if (empty($page))
1280
					$page = "/";
1281
				header("Location: {$page}");
1282
			}
1283
			exit;
1284
		} else {
1285
			/* give the user an error message */
1286
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1287
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1288
			if(isAjax()) {
1289
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1290
				return;
1291
			}
1292
		}
1293
	}
1294

    
1295
	/* Show login page if they aren't logged in */
1296
	if (empty($_SESSION['Logged_In']))
1297
		return false;
1298

    
1299
	/* If session timeout isn't set, we don't mark sessions stale */
1300
	if (!isset($config['system']['webgui']['session_timeout'])) {
1301
		/* Default to 4 hour timeout if one is not set */
1302
		if ($_SESSION['last_access'] < (time() - 14400)) {
1303
			$_GET['logout'] = true;
1304
			$_SESSION['Logout'] = true;
1305
		} else
1306
			$_SESSION['last_access'] = time();	
1307
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1308
		/* only update if it wasn't ajax */
1309
		if (!isAjax())
1310
			$_SESSION['last_access'] = time();
1311
	} else {
1312
		/* Check for stale session */
1313
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1314
			$_GET['logout'] = true;
1315
			$_SESSION['Logout'] = true;
1316
		} else {
1317
			/* only update if it wasn't ajax */
1318
			if (!isAjax())
1319
				$_SESSION['last_access'] = time();
1320
		}
1321
	}
1322

    
1323
	/* user hit the logout button */
1324
	if (isset($_GET['logout'])) {
1325

    
1326
		if ($_SESSION['Logout'])
1327
			log_error("Session timed out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1328
		else
1329
			log_error("User logged out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1330

    
1331
		/* wipe out $_SESSION */
1332
		$_SESSION = array();
1333

    
1334
		if (isset($_COOKIE[session_name()]))
1335
			setcookie(session_name(), '', time()-42000, '/');
1336

    
1337
		/* and destroy it */
1338
		session_destroy();
1339

    
1340
		$scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
1341
		$scriptElms = count($scriptName);
1342
		$scriptName = $scriptName[$scriptElms-1];
1343

    
1344
		if (isAjax())
1345
			return false;
1346

    
1347
		/* redirect to page the user is on, it'll prompt them to login again */
1348
		Header("Location: {$scriptName}");
1349

    
1350
		return false;
1351
	}
1352

    
1353
	/*
1354
	 * this is for debugging purpose if you do not want to use Ajax
1355
	 * to submit a HTML form. It basically diables the observation
1356
	 * of the submit event and hence does not trigger Ajax.
1357
	 */
1358
	if ($_GET['disable_ajax'])
1359
		$_SESSION['NO_AJAX'] = "True";
1360

    
1361
	/*
1362
	 * Same to re-enable Ajax.
1363
	 */
1364
	if ($_GET['enable_ajax'])
1365
		unset($_SESSION['NO_AJAX']);
1366

    
1367
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1368
	return true;
1369
}
1370

    
1371
?>
(4-4/62)