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))
291
				continue;
292
			if ($line[2] < 2000)
293
				continue;
294
			if ($line[2] > 65000)
295
				continue;
296
			$cmd = "/usr/sbin/pw userdel {$line[2]}";
297
			if($debug)
298
				log_error("Running: {$cmd}");
299
			mwexec($cmd);
300
		}
301
		pclose($fd);
302
	}
303

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

    
324
	/* make sure the all group exists */
325
	$allgrp = getGroupEntryByGID(1998);
326
	local_group_set($allgrp, true);
327

    
328
	/* sync all local users */
329
	if (is_array($config['system']['user']))
330
		foreach ($config['system']['user'] as $user)
331
			local_user_set($user);
332

    
333
	/* sync all local groups */
334
	if (is_array($config['system']['group']))
335
		foreach ($config['system']['group'] as $group)
336
			local_group_set($group);
337

    
338
	conf_mount_ro();
339

    
340
}
341

    
342
function local_user_set(& $user) {
343
	global $g, $debug;
344

    
345
	if (empty($user['password'])) {
346
		log_error("There is something wrong in your config because user {$user['name']} password is missing!");
347
		return;
348
	}
349

    
350
	conf_mount_rw();
351

    
352
	$home_base = "/home/";	
353
	$user_uid = $user['uid'];
354
	$user_name = $user['name'];
355
	$user_home = "{$home_base}{$user_name}";
356
	$user_shell = "/etc/rc.initial";
357
	$user_group = "nobody";
358

    
359
	// Ensure $home_base exists and is writable
360
	if (!is_dir($home_base)) 
361
		mkdir($home_base, 0755);
362

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

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

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

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

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

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

    
416
	if($debug)
417
		log_error("Running: {$cmd}");
418
	$fd = popen($cmd, "w");
419
	fwrite($fd, $user['password']);
420
	pclose($fd);
421

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

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

    
442
	$un = $lock_account ? "" : "un";
443
	exec("/usr/sbin/pw {$un}lock {$user_name} -q");
444
	
445
	conf_mount_ro();
446
}
447

    
448
function local_user_del($user) {
449
	global $debug;
450

    
451
	/* remove all memberships */
452
	local_user_set_groups($user);
453

    
454
	/* Don't remove /root */
455
	if ($user['uid'] != 0)
456
		$rmhome = "-r";
457

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

    
464
	if ($userattrs[0] != $user['name']) {
465
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
466
		return;
467
	}
468

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

    
472
	if($debug)
473
		log_error("Running: {$cmd}");
474
	mwexec($cmd);
475

    
476
	/* Delete user from groups needs a call to write_config() */
477
	local_group_del_user($user);
478
}
479

    
480
function local_user_set_password(& $user, $password) {
481

    
482
	$user['password'] = crypt($password);
483
	$user['md5-hash'] = md5($password);
484

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

    
493
	// Generate the NT-HASH from the unicode string
494
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
495
}
496

    
497
function local_user_get_groups($user, $all = false) {
498
	global $debug, $config;
499

    
500
	$groups = array();
501
	if (!is_array($config['system']['group']))
502
		return $groups;
503

    
504
	foreach ($config['system']['group'] as $group)
505
		if ( $all || ( !$all && ($group['name'] != "all")))
506
			if (is_array($group['member']))
507
				if (in_array($user['uid'], $group['member']))
508
					$groups[] = $group['name'];
509

    
510
	if ( $all )
511
		$groups[] = "all";
512

    
513
	sort($groups);
514

    
515
	return $groups;
516
	
517
}
518

    
519
function local_user_set_groups($user, $new_groups = NULL ) {
520
	global $debug, $config, $groupindex;
521

    
522
	if (!is_array($config['system']['group']))
523
		return;
524

    
525
	$cur_groups = local_user_get_groups($user, true);
526
	$mod_groups = array();
527

    
528
	if (!is_array($new_groups))
529
		$new_groups = array();
530

    
531
	if (!is_array($cur_groups))
532
		$cur_groups = array();
533

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

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

    
559
	/* sync all modified groups */
560
	foreach ($mod_groups as $group)
561
		local_group_set($group);
562
}
563

    
564
function local_group_del_user($user) {
565
	global $config;
566

    
567
	if (!is_array($config['system']['group']))
568
                return;
569

    
570
        foreach ($config['system']['group'] as $group) {
571
		if (is_array($group['member'])) {
572
			foreach ($group['member'] as $idx => $uid) {
573
				if ($user['uid'] == $uid)
574
					unset($config['system']['group']['member'][$idx]);
575
			}
576
		}
577
	}
578
}
579

    
580
function local_group_set($group, $reset = false) {
581
	global $debug;
582

    
583
	$group_name = $group['name'];
584
	$group_gid = $group['gid'];
585
	$group_members = "''";
586
	if (!$reset && !empty($group['member']) && count($group['member']) > 0)
587
		$group_members = implode(",",$group['member']);
588

    
589
	/* read from group db */
590
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
591
	$pwread = fgets($fd);
592
	pclose($fd);
593

    
594
	/* determine add or mod */
595
	if (!strncmp($pwread, "pw:", 3))
596
		$group_op = "groupadd";
597
	else
598
		$group_op = "groupmod";
599

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

    
603
	if($debug)
604
		log_error("Running: {$cmd}");
605
	mwexec($cmd);
606

    
607
}
608

    
609
function local_group_del($group) {
610
	global $debug;
611

    
612
	/* delete from group db */
613
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
614

    
615
	if($debug)
616
		log_error("Running: {$cmd}");
617
	mwexec($cmd);
618
}
619

    
620
function ldap_test_connection($authcfg) {
621
	global $debug, $config, $g;
622

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

    
638
        /* first check if there is even an LDAP server populated */
639
        if(!$ldapserver)
640
                return false;
641

    
642
        /* Setup CA environment if needed. */
643
        ldap_setup_caenv($authcfg);
644

    
645
        /* connect and see if server is up */
646
        $error = false;
647
	if (!($ldap = ldap_connect($ldapserver)))
648
		$error = true;
649

    
650
        if ($error == true) {
651
                log_error("ERROR!  Could not connect to server {$ldapname}.");
652
                return false;
653
        }
654

    
655
	return true;
656
}
657

    
658
function ldap_setup_caenv($authcfg) {
659
	global $g;
660
	require_once("certs.inc");
661

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

    
687
function ldap_test_bind($authcfg) {
688
	global $debug, $config, $g;
689

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

    
710
	/* first check if there is even an LDAP server populated */
711
        if(!$ldapserver)
712
                return false;
713

    
714
	/* Setup CA environment if needed. */
715
	ldap_setup_caenv($authcfg);
716

    
717
        /* connect and see if server is up */
718
        $error = false;
719
	if (!($ldap = ldap_connect($ldapserver)))
720
		$error = true;
721

    
722
        if ($error == true) {
723
                log_error("ERROR!  Could not connect to server {$ldapname}.");
724
                return false;
725
        }
726

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

    
740
	@ldap_unbind($ldap);
741

    
742
	return true;
743
}
744

    
745
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
746
	global $debug, $config, $g;
747

    
748
	if(!function_exists("ldap_connect"))
749
		return;
750

    
751
	$ous = array();
752

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

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

    
782
	/* Setup CA environment if needed. */
783
	ldap_setup_caenv($authcfg);
784

    
785
	/* connect and see if server is up */
786
        $error = false;
787
	if (!($ldap = ldap_connect($ldapserver)))
788
		$error = true;
789

    
790
        if ($error == true) {
791
		log_error("ERROR!  Could not connect to server {$ldapname}.");
792
                return $ous;
793
        }
794

    
795
	$ldapfilter = "(|(ou=*)(cn=Users))";
796

    
797
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
798
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
799

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

    
812
	if ($ldapscope == "one")
813
		$ldapfunc = "ldap_list";
814
	else
815
		$ldapfunc = "ldap_search";
816

    
817
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
818
	$info = @ldap_get_entries($ldap, $search);
819

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

    
835
	@ldap_unbind($ldap);
836

    
837
	return $ous;
838
}
839

    
840
function ldap_get_groups($username, $authcfg) {
841
	global $debug, $config;
842
	
843
	if(!function_exists("ldap_connect"))
844
		return;
845
	
846
	if(!$username) 
847
		return false;
848

    
849
	if(stristr($username, "@")) {
850
		$username_split=split("\@", $username);
851
		$username = $username_split[0];		
852
	}
853

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

    
888
	$ldapdn             = $_SESSION['ldapdn'];
889

    
890
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
891
	$ldapgroupattribute = strtolower($ldapgroupattribute);
892
	$memberof = array();
893

    
894
        /* Setup CA environment if needed. */
895
        ldap_setup_caenv($authcfg);
896

    
897
	/* connect and see if server is up */
898
	$error = false;
899
	if (!($ldap = ldap_connect($ldapserver)))
900
		$error = true;
901

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

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

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

    
932
	$search    = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
933
	$info      = @ldap_get_entries($ldap, $search);
934

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

    
957
function ldap_backed($username, $passwd, $authcfg) {
958
	global $debug, $config;
959
	
960
	if(!$username) 
961
		return;
962

    
963
	if(!function_exists("ldap_connect"))
964
		return;
965

    
966
	if(stristr($username, "@")) {
967
		$username_split=split("\@", $username);
968
		$username = $username_split[0];        
969
	}
970
	if(stristr($username, "\\")) {
971
		$username_split=split("\\", $username);
972
		$username = $username_split[0];        
973
	}
974

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

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

    
1009
		return false;
1010
	}
1011
	
1012
        /* Setup CA environment if needed. */
1013
        ldap_setup_caenv($authcfg);
1014

    
1015
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1016
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1017

    
1018
	/* Make sure we can connect to LDAP */
1019
	$error = false;
1020
	if (!($ldap = ldap_connect($ldapserver)))
1021
		$error = true;
1022

    
1023
	if ($error == true) {
1024
		log_error("ERROR!  Could not connect to server {$ldapname}.");
1025
		return false;
1026
	}
1027

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

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

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

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

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

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

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

    
1102
	return true;
1103
}
1104

    
1105
function radius_backed($username, $passwd, $authcfg){
1106
	global $debug, $config;
1107
	$ret = false;
1108

    
1109
	require_once("radius.inc");
1110

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

    
1120
	/* Add a new servers to our instance */
1121
	foreach ($radiusservers as $radsrv)
1122
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
1123

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

    
1131
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1132

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

    
1151
	// close OO RADIUS_AUTHENTICATION
1152
	$rauth->close();
1153

    
1154
	return $ret;
1155
}
1156

    
1157
function get_user_expiration_date($username) {
1158
	$user = getUserEntry($username);
1159
	if ($user['expires']) 
1160
		return $user['expires'];
1161
}
1162

    
1163
function is_account_expired($username) {
1164
	$expirydate = get_user_expiration_date($username);
1165
	if ($expirydate) {
1166
		if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($expirydate))))
1167
			return true;
1168
	}
1169

    
1170
	return false;
1171
}
1172

    
1173
function is_account_disabled($username) {
1174
	$user = getUserEntry($username);
1175
	if (isset($user['disabled']))
1176
		return true;
1177

    
1178
	return false;
1179
}
1180

    
1181
function auth_get_authserver($name) {
1182
        global $config;
1183

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

    
1194
function auth_get_authserver_list() {
1195
        global $config;
1196

    
1197
	$list = array();
1198

    
1199
        if (is_array($config['system']['authserver'])) {
1200
                foreach ($config['system']['authserver'] as $authcfg) {
1201
			/* Add support for disabled entries? */
1202
			$list[$authcfg['name']] = $authcfg;
1203
                }
1204
        }
1205

    
1206
	$list["Local Database"] = array( "name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1207
	return $list;
1208
}
1209

    
1210
function getUserGroups($username, $authcfg) {
1211
	global $config;
1212

    
1213
	$allowed_groups = array();
1214

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

    
1227
	$member_groups = array();
1228
        if (is_array($config['system']['group'])) {
1229
                foreach ($config['system']['group'] as $group)
1230
                        if (in_array($group['name'], $allowed_groups))
1231
				$member_groups[] = $group['name'];
1232
	}
1233

    
1234
	return $member_groups;
1235
}
1236

    
1237
function authenticate_user($username, $password, $authcfg = NULL) {
1238

    
1239
	if (!$authcfg) {
1240
		return local_backed($username, $password);
1241
	}
1242

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

    
1260
	return $authenticated;
1261
}
1262

    
1263
function session_auth() {
1264
	global $HTTP_SERVER_VARS, $config, $_SESSION, $page;
1265

    
1266
	session_start();
1267

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

    
1299
	/* Show login page if they aren't logged in */
1300
	if (empty($_SESSION['Logged_In']))
1301
		return false;
1302

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

    
1327
	/* user hit the logout button */
1328
	if (isset($_GET['logout'])) {
1329

    
1330
		if ($_SESSION['Logout'])
1331
			log_error("Session timed out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1332
		else
1333
			log_error("User logged out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1334

    
1335
		/* wipe out $_SESSION */
1336
		$_SESSION = array();
1337

    
1338
		if (isset($_COOKIE[session_name()]))
1339
			setcookie(session_name(), '', time()-42000, '/');
1340

    
1341
		/* and destroy it */
1342
		session_destroy();
1343

    
1344
		$scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
1345
		$scriptElms = count($scriptName);
1346
		$scriptName = $scriptName[$scriptElms-1];
1347

    
1348
		if (isAjax())
1349
			return false;
1350

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

    
1354
		return false;
1355
	}
1356

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

    
1365
	/*
1366
	 * Same to re-enable Ajax.
1367
	 */
1368
	if ($_GET['enable_ajax'])
1369
		unset($_SESSION['NO_AJAX']);
1370

    
1371
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1372
	return true;
1373
}
1374

    
1375
?>
(4-4/62)