Project

General

Profile

Download (38.6 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

    
61
	if(strstr($_SERVER['HTTP_HOST'], ":")) {
62
		$http_host_port = explode(":", $_SERVER['HTTP_HOST']);
63
		/* v6 address has more parts, drop the last part */
64
		if(count($http_host_port) > 1) {
65
			array_pop($http_host_port);
66
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
67
		} else {
68
			$http_host = $http_host_port[0];
69
		}
70
	} else {
71
		$http_host = $_SERVER['HTTP_HOST'];
72
	}
73
	if(is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
74
			strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1")
75
		$found_host = true;
76
	if(strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
77
			strcasecmp($http_host, $config['system']['hostname']) == 0)
78
		$found_host = true;
79

    
80
	if(is_array($config['dyndnses']['dyndns']) && !$found_host)
81
		foreach($config['dyndnses']['dyndns'] as $dyndns)
82
			if(strcasecmp($dyndns['host'], $http_host) == 0) {
83
				$found_host = true;
84
				break;
85
			}
86

    
87
	if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
88
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
89
		foreach ($althosts as $ah)
90
			if(strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
91
				$found_host = true;
92
				break;
93
			}
94
	}
95

    
96
	if($found_host == false) {
97
		if(!security_checks_disabled()) {
98
			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.");
99
			exit;
100
		}
101
		$security_passed = false;
102
	}
103
}
104

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

    
157
if (function_exists("display_error_form") && $security_passed)
158
	/* Security checks passed, so it should be OK to turn them back on */
159
	restore_security_checks();
160
unset($security_passed);
161

    
162
$groupindex = index_groups();
163
$userindex = index_users();
164

    
165
function index_groups() {
166
	global $g, $debug, $config, $groupindex;
167

    
168
	$groupindex = array();
169

    
170
	if (is_array($config['system']['group'])) {
171
		$i = 0;
172
		foreach($config['system']['group'] as $groupent) {
173
			$groupindex[$groupent['name']] = $i;
174
			$i++;
175
		}
176
	}
177

    
178
	return ($groupindex);
179
}
180

    
181
function index_users() {
182
	global $g, $debug, $config;
183

    
184
	if (is_array($config['system']['user'])) {
185
		$i = 0;
186
		foreach($config['system']['user'] as $userent) {
187
			$userindex[$userent['name']] = $i;
188
			$i++;
189
		}
190
	}
191

    
192
	return ($userindex);
193
}
194

    
195
function & getUserEntry($name) {
196
	global $debug, $config, $userindex;
197
	if (isset($userindex[$name]))
198
		return $config['system']['user'][$userindex[$name]];
199
}
200

    
201
function & getUserEntryByUID($uid) {
202
	global $debug, $config;
203
	foreach ($config['system']['user'] as & $user)
204
		if ($user['uid'] == $uid)
205
			return $user;
206

    
207
	return false;
208
}
209

    
210
function & getGroupEntry($name) {
211
	global $debug, $config, $groupindex;
212
	if (isset($groupindex[$name]))
213
		return $config['system']['group'][$groupindex[$name]];
214
}
215

    
216
function & getGroupEntryByGID($gid) {
217
	global $debug, $config;
218
	foreach ($config['system']['group'] as & $group)
219
		if ($group['gid'] == $gid)
220
			return $group;
221

    
222
	return false;
223
}
224

    
225
function get_user_privileges(& $user) {
226

    
227
        $privs = $user['priv'];
228
        if (!is_array($privs))
229
                $privs = array();
230

    
231
        $names = local_user_get_groups($user, true);
232

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

    
239
        return $privs;
240
}
241

    
242
function userHasPrivilege($userent, $privid = false) {
243

    
244
        if (!$privid || !is_array($userent))
245
                return false;
246

    
247
        $privs = get_user_privileges($userent);
248

    
249
        if (!is_array($privs))
250
                return false;
251

    
252
        if (!in_array($privid, $privs))
253
                return false;
254

    
255
        return true;
256
}
257

    
258
function local_backed($username, $passwd) {
259

    
260
	$user = getUserEntry($username);
261
	if (!$user)
262
		return false;
263

    
264
	if (is_account_disabled($username) || is_account_expired($username))
265
		return false;
266

    
267
	if ($user['password'])
268
	{
269
		$passwd = crypt($passwd, $user['password']);
270
		if ($passwd == $user['password'])
271
			return true;
272
	}
273

    
274
	if ($user['md5-hash'])
275
	{
276
		$passwd = md5($passwd);
277
		if ($passwd == $user['md5-hash'])
278
			return true;
279
	}
280

    
281
	return false;
282
}
283

    
284
function local_sync_accounts() {
285
	global $debug, $config;
286
	conf_mount_rw();
287

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

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

    
327
	/* make sure the all group exists */
328
	$allgrp = getGroupEntryByGID(1998);
329
	local_group_set($allgrp, true);
330

    
331
	/* sync all local users */
332
	if (is_array($config['system']['user']))
333
		foreach ($config['system']['user'] as $user)
334
			local_user_set($user);
335

    
336
	/* sync all local groups */
337
	if (is_array($config['system']['group']))
338
		foreach ($config['system']['group'] as $group)
339
			local_group_set($group);
340

    
341
	conf_mount_ro();
342

    
343
}
344

    
345
function local_user_set(& $user) {
346
	global $g, $debug;
347

    
348
	conf_mount_rw();
349

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

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

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

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

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

    
396
	/* read from pw db */
397
	$fd = popen("/usr/sbin/pw usershow {$user_name} 2>&1", "r");
398
	$pwread = fgets($fd);
399
	pclose($fd);
400

    
401
	/* determine add or mod */
402
	if (!strncmp($pwread, "pw:", 3)) {
403
		$user_op = "useradd -m -k /etc/skel -o";
404
	} else {
405
		$user_op = "usermod";
406
	}
407

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

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

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

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

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

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

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

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

    
455
	/* delete from pw db */
456
	$cmd = "/usr/sbin/pw userdel {$user['name']} {$rmhome}";
457

    
458
	if($debug)
459
		log_error("Running: {$cmd}");
460
	mwexec($cmd);
461

    
462
	/* Delete user from groups needs a call to write_config() */
463
	local_group_del_user($user);
464
}
465

    
466
function local_user_set_password(& $user, $password) {
467

    
468
	$user['password'] = crypt($password);
469
	$user['md5-hash'] = md5($password);
470

    
471
	// Converts ascii to unicode.
472
	$astr = (string) $password;
473
	$ustr = '';
474
	for ($i = 0; $i < strlen($astr); $i++) {
475
		$a = ord($astr{$i}) << 8;
476
		$ustr.= sprintf("%X", $a);
477
	}
478

    
479
	// Generate the NT-HASH from the unicode string
480
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
481
}
482

    
483
function local_user_get_groups($user, $all = false) {
484
	global $debug, $config;
485

    
486
	$groups = array();
487
	if (!is_array($config['system']['group']))
488
		return $groups;
489

    
490
	foreach ($config['system']['group'] as $group)
491
		if ( $all || ( !$all && ($group['name'] != "all")))
492
			if (is_array($group['member']))
493
				if (in_array($user['uid'], $group['member']))
494
					$groups[] = $group['name'];
495

    
496
	if ( $all )
497
		$groups[] = "all";
498

    
499
	sort($groups);
500

    
501
	return $groups;
502
	
503
}
504

    
505
function local_user_set_groups($user, $new_groups = NULL ) {
506
	global $debug, $config, $groupindex;
507

    
508
	if (!is_array($config['system']['group']))
509
		return;
510

    
511
	$cur_groups = local_user_get_groups($user, true);
512
	$mod_groups = array();
513

    
514
	if (!is_array($new_groups))
515
		$new_groups = array();
516

    
517
	if (!is_array($cur_groups))
518
		$cur_groups = array();
519

    
520
	/* determine which memberships to add */
521
	foreach ($new_groups as $groupname) {
522
		if (in_array($groupname,$cur_groups))
523
			continue;
524
		$group = & $config['system']['group'][$groupindex[$groupname]];
525
		$group['member'][] = $user['uid'];
526
		$mod_groups[] = $group;
527
	}
528
	unset($group);
529

    
530
	/* determine which memberships to remove */
531
	foreach ($cur_groups as $groupname) {
532
		if (in_array($groupname,$new_groups))
533
			continue;
534
		if (!isset($config['system']['group'][$groupindex[$groupname]]))
535
			continue;
536
		$group = & $config['system']['group'][$groupindex[$groupname]];
537
		if (is_array($group['member'])) {
538
			$index = array_search($user['uid'], $group['member']);
539
			array_splice($group['member'], $index, 1);
540
			$mod_groups[] = $group;
541
		}
542
	}
543
	unset($group);
544

    
545
	/* sync all modified groups */
546
	foreach ($mod_groups as $group)
547
		local_group_set($group);
548
}
549

    
550
function local_group_del_user($user) {
551
	global $config;
552

    
553
	if (!is_array($config['system']['group']))
554
                return;
555

    
556
        foreach ($config['system']['group'] as $group) {
557
		if (is_array($group['member'])) {
558
			foreach ($group['member'] as $idx => $uid) {
559
				if ($user['uid'] == $uid)
560
					unset($config['system']['group']['member'][$idx]);
561
			}
562
		}
563
	}
564
}
565

    
566
function local_group_set($group, $reset = false) {
567
	global $debug;
568

    
569
	$group_name = $group['name'];
570
	$group_gid = $group['gid'];
571
	$group_members = "''";
572
	if (!$reset && !empty($group['member']) && count($group['member']) > 0)
573
		$group_members = implode(",",$group['member']);
574

    
575
	/* read from group db */
576
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
577
	$pwread = fgets($fd);
578
	pclose($fd);
579

    
580
	/* determine add or mod */
581
	if (!strncmp($pwread, "pw:", 3))
582
		$group_op = "groupadd";
583
	else
584
		$group_op = "groupmod";
585

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

    
589
	if($debug)
590
		log_error("Running: {$cmd}");
591
	mwexec($cmd);
592

    
593
}
594

    
595
function local_group_del($group) {
596
	global $debug;
597

    
598
	/* delete from group db */
599
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
600

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

    
606
function ldap_test_connection($authcfg) {
607
	global $debug, $config, $g;
608

    
609
	if ($authcfg) {
610
                if (strstr($authcfg['ldap_urltype'], "Standard"))
611
                        $ldapproto = "ldap";
612
                else
613
                        $ldapproto = "ldaps";
614
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
615
                $ldapport           = $authcfg['ldap_port'];
616
                $ldapbasedn         = $authcfg['ldap_basedn'];
617
                $ldapbindun         = $authcfg['ldap_binddn'];
618
                $ldapbindpw         = $authcfg['ldap_bindpw'];
619
        } else
620
		return false;
621

    
622
        /* first check if there is even an LDAP server populated */
623
        if(!$ldapserver)
624
                return false;
625

    
626
        /* connect and see if server is up */
627
        putenv('LDAPTLS_REQCERT=never');
628
        $error = false;
629
        if (empty($ldapport)) {
630
                if (!($ldap = ldap_connect($ldapserver)))
631
                        $error = true;
632
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
633
                $error = true;
634

    
635
        if ($error == true) {
636
                log_error("ERROR!  Could not connect to server {$ldapname}.");
637
                return false;
638
        }
639

    
640
	return true;
641
}
642

    
643
function ldap_test_bind($authcfg) {
644
	global $debug, $config, $g;
645

    
646
	if ($authcfg) {
647
                if (strstr($authcfg['ldap_urltype'], "Standard"))
648
                        $ldapproto = "ldap";
649
                else
650
                        $ldapproto = "ldaps";
651
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
652
                $ldapport           = $authcfg['ldap_port'];
653
                $ldapbasedn         = $authcfg['ldap_basedn'];
654
                $ldapbindun         = $authcfg['ldap_binddn'];
655
                $ldapbindpw         = $authcfg['ldap_bindpw'];
656
                $ldapver            = $authcfg['ldap_protver'];
657
		if (empty($ldapbndun) || empty($ldapbindpw))
658
                        $ldapanon = true;
659
                else
660
                        $ldapanon = false;
661
	} else
662
		return false;
663

    
664
	/* first check if there is even an LDAP server populated */
665
        if(!$ldapserver)
666
                return false;
667

    
668
        /* connect and see if server is up */
669
        putenv('LDAPTLS_REQCERT=never');
670
        $error = false;
671
        if (empty($ldapport)) {
672
                if (!($ldap = ldap_connect($ldapserver)))
673
                        $error = true;
674
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
675
                $error = true;
676

    
677
        if ($error == true) {
678
                log_error("ERROR!  Could not connect to server {$ldapname}.");
679
                return false;
680
        }
681

    
682
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
683
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
684
 
685
	if ($ldapanon == true) {
686
		if (!($res = @ldap_bind($ldap))) {
687
			@ldap_close($ldap);
688
			return false;
689
		}
690
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
691
		@ldap_close($ldap);
692
		return false;
693
	}
694

    
695
	@ldap_unbind($ldap);
696

    
697
	return true;
698
}
699

    
700
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
701
	global $debug, $config, $g;
702

    
703
	if(!function_exists("ldap_connect"))
704
		return;
705

    
706
	$ous = array();
707

    
708
	if ($authcfg) {
709
                if (strstr($authcfg['ldap_urltype'], "Standard"))
710
                        $ldapproto = "ldap";
711
                else
712
                        $ldapproto = "ldaps";
713
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
714
                $ldapport           = $authcfg['ldap_port'];
715
                $ldapbasedn         = $authcfg['ldap_basedn'];
716
                $ldapbindun         = $authcfg['ldap_binddn'];
717
                $ldapbindpw         = $authcfg['ldap_bindpw'];
718
                $ldapver            = $authcfg['ldap_protver'];
719
		if (empty($ldapbindun) || empty($ldapbindpw))
720
                        $ldapanon = true;
721
                else
722
                        $ldapanon = false;
723
                $ldapname           = $authcfg['name'];
724
                $ldapfallback       = false;
725
		$ldapscope          = $authcfg['ldap_scope'];
726
        } else
727
		return false;
728

    
729
        /* first check if there is even an LDAP server populated */
730
        if(!$ldapserver) {
731
                log_error("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined.");
732
                return $ous;
733
        }
734

    
735
	/* connect and see if server is up */
736
        putenv('LDAPTLS_REQCERT=never');
737
        $error = false;
738
        if (empty($ldapport)) {
739
                if (!($ldap = ldap_connect($ldapserver)))
740
                        $error = true;
741
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
742
                $error = true;
743

    
744
        if ($error == true) {
745
		log_error("ERROR!  Could not connect to server {$ldapname}.");
746
                return $ous;
747
        }
748

    
749
	$ldapfilter = "(|(ou=*)(cn=Users))";
750

    
751
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
752
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
753

    
754
	if ($ldapanon == true) {
755
                if (!($res = @ldap_bind($ldap))) {
756
			log_error("ERROR! ldap_get_user_ous() could not bind anonymously to server {$ldapname}.");
757
			@ldap_close($ldap);
758
                        return $ous;
759
		}
760
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
761
		log_error("ERROR! ldap_get_user_ous() could not bind to server {$ldapname}.");
762
		@ldap_close($ldap);
763
		return $ous;
764
	}
765

    
766
	if ($ldapscope == "one")
767
		$ldapfunc = "ldap_list";
768
	else
769
		$ldapfunc = "ldap_search";
770

    
771
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
772
	$info = @ldap_get_entries($ldap, $search);
773

    
774
	if (is_array($info)) {
775
		foreach ($info as $inf) {
776
			if (!$show_complete_ou) {
777
				$inf_split = split(",", $inf['dn']);
778
				$ou = $inf_split[0];
779
				$ou = str_replace("OU=","", $ou);
780
				$ou = str_replace("CN=","", $ou);
781
			} else
782
				if($inf['dn'])
783
					$ou = $inf['dn'];
784
			if($ou)
785
				$ous[] = $ou;
786
		}
787
	}
788

    
789
	@ldap_unbind($ldap);
790

    
791
	return $ous;
792
}
793

    
794
function ldap_get_groups($username, $authcfg) {
795
	global $debug, $config;
796
	
797
	if(!function_exists("ldap_connect"))
798
		return;
799
	
800
	if(!$username) 
801
		return false;
802

    
803
	if(stristr($username, "@")) {
804
		$username_split=split("\@", $username);
805
		$username = $username_split[0];		
806
	}
807

    
808
	if(stristr($username, "\\")) {
809
		$username_split=split("\\", $username);
810
		$username = $username_split[0];        
811
	}    
812
	
813
	//log_error("Getting LDAP groups for {$username}.");
814
        if ($authcfg) {
815
                if (strstr($authcfg['ldap_urltype'], "Standard"))
816
                        $ldapproto = "ldap";
817
                else
818
                        $ldapproto = "ldaps";
819
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
820
                $ldapport           = $authcfg['ldap_port'];
821
                $ldapbasedn         = $authcfg['ldap_basedn'];
822
                $ldapbindun         = $authcfg['ldap_binddn'];
823
                $ldapbindpw         = $authcfg['ldap_bindpw'];
824
                $ldapauthcont       = $authcfg['ldap_authcn'];
825
                $ldapnameattribute  = strtolower($authcfg['ldap_attr_user']);
826
                $ldapgroupattribute  = strtolower($authcfg['ldap_attr_member']);
827
                $ldapfilter         = "({$ldapnameattribute}={$username})";
828
                $ldaptype           = "";
829
                $ldapver            = $authcfg['ldap_protver'];
830
		if (empty($ldapbindun) || empty($ldapbindpw))
831
                        $ldapanon = true;
832
                else
833
                        $ldapanon = false;
834
                $ldapname           = $authcfg['name'];
835
                $ldapfallback       = false;
836
		$ldapscope          = $authcfg['ldap_scope'];
837
	} else
838
		return false;
839

    
840
	$ldapdn             = $_SESSION['ldapdn'];
841

    
842
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
843
	$ldapgroupattribute = strtolower($ldapgroupattribute);
844
	$memberof = array();
845

    
846
	/* connect and see if server is up */
847
	putenv('LDAPTLS_REQCERT=never');
848
	$error = false;
849
        if (empty($ldapport)) {
850
                if (!($ldap = ldap_connect($ldapserver)))
851
                        $error = true;
852
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
853
                $error = true;
854

    
855
	if ($error == true) {
856
		log_error("ERROR! ldap_get_groups() Could not connect to server {$ldapname}.");
857
                return memberof;
858
        }
859
    
860
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
861
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
862

    
863
	/* bind as user that has rights to read group attributes */
864
	if ($ldapanon == true) {
865
                if (!($res = @ldap_bind($ldap))) {
866
			log_error("ERROR! ldap_get_groups() could not bind anonymously to server {$ldapname}.");
867
			@ldap_close($ldap);
868
                        return false;
869
		}
870
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
871
		log_error("ERROR! ldap_get_groups() could not bind to server {$ldapname}.");
872
		@ldap_close($ldap);
873
		return memberof;
874
	}
875

    
876
	/* get groups from DN found */
877
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
878
	/* since we know the DN is in $_SESSION['ldapdn'] */
879
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
880
	if ($ldapscope == "one")
881
                $ldapfunc = "ldap_list";
882
        else
883
                $ldapfunc = "ldap_search";
884

    
885
	$search    = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
886
	$info      = @ldap_get_entries($ldap, $search);
887

    
888
	$countem = $info["count"];	
889
	
890
	if(is_array($info[0][$ldapgroupattribute])) {
891
		/* Iterate through the groups and throw them into an array */
892
		foreach ($info[0][$ldapgroupattribute] as $member) {
893
			if (stristr($member, "CN=") !== false) {
894
				$membersplit = split(",", $member);
895
				$memberof[] = preg_replace("/CN=/i", "", $membersplit[0]);
896
			}
897
		}
898
	}
899
	
900
	/* Time to close LDAP connection */
901
	@ldap_unbind($ldap);
902
	
903
	$groups = print_r($memberof,true);
904
	
905
	//log_error("Returning groups ".$groups." for user $username");
906
	
907
	return $memberof;
908
}
909

    
910
function ldap_backed($username, $passwd, $authcfg) {
911
	global $debug, $config;
912
	
913
	if(!$username) 
914
		return;
915

    
916
	if(!function_exists("ldap_connect"))
917
		return;
918

    
919
	if(stristr($username, "@")) {
920
		$username_split=split("\@", $username);
921
		$username = $username_split[0];        
922
	}
923
	if(stristr($username, "\\")) {
924
		$username_split=split("\\", $username);
925
		$username = $username_split[0];        
926
	}
927

    
928
	if ($authcfg) {
929
		if (strstr($authcfg['ldap_urltype'], "Standard"))
930
			$ldapproto = "ldap";
931
		else
932
			$ldapproto = "ldaps";
933
		$ldapserver         = "{$ldapproto}://{$authcfg['host']}";
934
		$ldapport	    = $authcfg['ldap_port'];
935
                $ldapbasedn         = $authcfg['ldap_basedn'];
936
                $ldapbindun         = $authcfg['ldap_binddn'];
937
                $ldapbindpw         = $authcfg['ldap_bindpw'];
938
		if (empty($ldapbindun) || empty($ldapbindpw))
939
			$ldapanon = true;
940
		else
941
			$ldapanon = false;
942
                $ldapauthcont       = $authcfg['ldap_authcn'];
943
                $ldapnameattribute  = strtolower($authcfg['ldap_attr_user']);
944
                $ldapfilter         = "({$ldapnameattribute}={$username})";
945
                $ldaptype           = "";
946
                $ldapver            = $authcfg['ldap_protver'];
947
		$ldapname	    = $authcfg['name'];
948
		$ldapscope	    = $authcfg['ldap_scope'];
949
	} else
950
		return false;
951

    
952
	/* first check if there is even an LDAP server populated */ 
953
	if(!$ldapserver) {
954
		if ($ldapfallback) {
955
			log_error("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager.");
956
			return local_backed($username, $passwd);
957
		} else
958
			log_error("ERROR! ldap_backed() called with no LDAP authentication server defined.");
959

    
960
		return false;
961
	}
962
	
963
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
964
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
965

    
966
	/* Make sure we can connect to LDAP */
967
	putenv('LDAPTLS_REQCERT=never');
968
	$error = false;
969
	if (empty($ldapport)) {
970
		if (!($ldap = ldap_connect($ldapserver)))
971
			$error = true;
972
	} else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
973
		$error = true;
974

    
975
	if ($error == true) {
976
		log_error("ERROR!  Could not connect to server {$ldapname}.");
977
		return false;
978
	}
979

    
980
	/* ok, its up.  now, lets bind as the bind user so we can search it */
981
	$error = false;
982
	if ($ldapanon == true) {
983
                if (!($res = @ldap_bind($ldap)))
984
                        $error = true;
985
	} else if (!($res = ldap_bind($ldap, $ldapbindun, $ldapbindpw)))
986
		$error = true;
987

    
988
	if ($error == true) {
989
		@ldap_close($ldap);
990
		log_error("ERROR! Could not bind to server {$ldapname}.");
991
		return false;
992
	}
993
	
994
	/* Get LDAP Authcontainers and split em up. */
995
	$ldac_splits = split(";", $ldapauthcont);
996
	
997
	/* setup the usercount so we think we havn't found anyone yet */
998
	$usercount  = 0;
999

    
1000
	/*****************************************************************/
1001
	/*  We First find the user based on username and filter          */
1002
	/*  Then, once we find the first occurance of that person        */
1003
	/*  We set seesion variables to ponit to the OU and DN of the    */
1004
	/*  Person.  To later be used by ldap_get_groups.                */
1005
	/*  that way we don't have to search twice.                      */
1006
	/*****************************************************************/
1007
	log_error("Now Searching for {$username} in directory.");
1008
	/* Iterate through the user containers for search */
1009
	foreach ($ldac_splits as $i => $ldac_split) {
1010
		/* Make sure we just use the first user we find */
1011
		log_error("Now Searching in server {$ldapname}, container {$ldac_split} with filter {$ldapfilter}.");
1012
		if ($ldapscope == "one")
1013
			$ldapfunc = "ldap_list";
1014
		else
1015
			$ldapfunc = "ldap_search";
1016
		/* Support legacy auth container specification. */
1017
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn))
1018
			$search	 = @$ldapfunc($ldap,$ldac_split,$ldapfilter);
1019
		else
1020
			$search  = @$ldapfunc($ldap,"{$ldac_split},{$ldapbasedn}",$ldapfilter);
1021
		if (!$search) {
1022
			log_error("Search resulted in error: " . ldap_error($ldap));
1023
			continue;
1024
		}
1025
		$info	 = ldap_get_entries($ldap,$search);
1026
		$matches = $info['count'];
1027
		if ($matches == 1){
1028
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1029
			$_SESSION['ldapou'] = $ldac_split[$i];
1030
			$_SESSION['ldapon'] = "true";
1031
			$usercount = 1;
1032
			break;
1033
		}
1034
	}
1035

    
1036
	if ($usercount != 1){
1037
		@ldap_unbind($ldap);
1038
		log_error("ERROR! Either LDAP search failed, or multiple users were found.");
1039
		return false;                         
1040
	}
1041

    
1042
	/* Now lets bind as the user we found */
1043
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1044
		log_error("ERROR! Could not login to server {$ldapname} as user {$username}.");
1045
		@ldap_unbind($ldap);
1046
		return false;
1047
	}
1048

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

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

    
1054
	return true;
1055
}
1056

    
1057
function radius_backed($username, $passwd, $authcfg){
1058
	global $debug, $config;
1059
	$ret = false;
1060

    
1061
	require_once("radius.inc");
1062

    
1063
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1064
	if ($authcfg) {
1065
		$radiusservers = array();
1066
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1067
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1068
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1069
	} else
1070
		return false;
1071

    
1072
	/* Add a new servers to our instance */
1073
	foreach ($radiusservers as $radsrv)
1074
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
1075

    
1076
	if (PEAR::isError($rauth->start())) {
1077
		$retvalue['auth_val'] = 1;
1078
		$retvalue['error'] = $rauth->getError();
1079
		if ($debug)
1080
			printf("Radius start: %s<br>\n", $retvalue['error']);
1081
	}
1082

    
1083
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1084

    
1085
	/* Send request */
1086
	$result = $rauth->send();
1087
	if (PEAR::isError($result)) {
1088
		$retvalue['auth_val'] = 1;
1089
		$retvalue['error'] = $result->getMessage();
1090
		if ($debug)
1091
			printf("Radius send failed: %s<br>\n", $retvalue['error']);
1092
	} else if ($result === true) {
1093
		$retvalue['auth_val'] = 2;
1094
		if ($debug)
1095
			printf(gettext("Radius Auth succeeded")."<br>\n");
1096
		$ret = true;
1097
	} else {
1098
		$retvalue['auth_val'] = 3;
1099
		if ($debug)
1100
			printf(gettext("Radius Auth rejected")."<br>\n");
1101
	}
1102

    
1103
	// close OO RADIUS_AUTHENTICATION
1104
	$rauth->close();
1105

    
1106
	return $ret;
1107
}
1108

    
1109
function get_user_expiration_date($username) {
1110
	$user = getUserEntry($username);
1111
	if ($user['expires']) 
1112
		return $user['expires'];
1113
}
1114

    
1115
function is_account_expired($username) {
1116
	$expirydate = get_user_expiration_date($username);
1117
	if ($expirydate) {
1118
		if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($expirydate))))
1119
			return true;
1120
	}
1121

    
1122
	return false;
1123
}
1124

    
1125
function is_account_disabled($username) {
1126
	$user = getUserEntry($username);
1127
	if (isset($user['disabled']))
1128
		return true;
1129

    
1130
	return false;
1131
}
1132

    
1133
function auth_get_authserver($name) {
1134
        global $config;
1135

    
1136
        if (is_array($config['system']['authserver'])) {
1137
                foreach ($config['system']['authserver'] as $authcfg) {
1138
                        if ($authcfg['name'] == $name)
1139
                                return $authcfg;
1140
                }
1141
        }
1142
	if ($name == "Local Database")
1143
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1144
}
1145

    
1146
function auth_get_authserver_list() {
1147
        global $config;
1148

    
1149
	$list = array();
1150

    
1151
        if (is_array($config['system']['authserver'])) {
1152
                foreach ($config['system']['authserver'] as $authcfg) {
1153
			/* Add support for disabled entries? */
1154
			$list[$authcfg['name']] = $authcfg;
1155
                }
1156
        }
1157

    
1158
	$list["Local Database"] = array( "name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1159
	return $list;
1160
}
1161

    
1162
function getUserGroups($username, $authcfg) {
1163
	global $config;
1164

    
1165
	$allowed_groups = array();
1166

    
1167
	switch($authcfg['type']) {
1168
        case 'ldap':
1169
		$allowed_groups = @ldap_get_groups($username, $authcfg);
1170
		break;
1171
	case 'radius':
1172
		break;
1173
	default:
1174
		$user = getUserEntry($username);
1175
		$allowed_groups = @local_user_get_groups($user, true);
1176
		break;
1177
	}
1178

    
1179
	$member_groups = array();
1180
        if (is_array($config['system']['group'])) {
1181
                foreach ($config['system']['group'] as $group)
1182
                        if (in_array($group['name'], $allowed_groups))
1183
				$member_groups[] = $group['name'];
1184
	}
1185

    
1186
	return $member_groups;
1187
}
1188

    
1189
function authenticate_user($username, $password, $authcfg = NULL) {
1190

    
1191
	if (!$authcfg) {
1192
		return local_backed($username, $password);
1193
	}
1194

    
1195
	$authenticated = false;
1196
	switch($authcfg['type']) {
1197
        case 'ldap':
1198
                if (ldap_backed($username, $password, $authcfg))
1199
                        $authenticated = true;
1200
                break;
1201
        case 'radius':
1202
                if (radius_backed($username, $password, $authcfg))
1203
                        $authenticated = true;
1204
                break;
1205
        default:
1206
                /* lookup user object by name */
1207
                if (local_backed($username, $password))
1208
                        $authenticated = true;
1209
                break;
1210
        }
1211

    
1212
	return $authenticated;
1213
}
1214

    
1215
function session_auth() {
1216
	global $HTTP_SERVER_VARS, $config, $_SESSION, $page;
1217

    
1218
	session_start();
1219

    
1220
	/* Validate incoming login request */
1221
	if (isset($_POST['login'])) {
1222
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1223
		if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) || 
1224
		    authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1225
			$_SESSION['Logged_In'] = "True";
1226
			$_SESSION['Username'] = $_POST['usernamefld'];
1227
			$_SESSION['last_access'] = time();
1228
			if(! isset($config['system']['webgui']['quietlogin'])) {
1229
				log_auth("Successful webConfigurator login for user '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1230
			}
1231
			$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1232
			if (isset($_POST['postafterlogin']))
1233
				return true;
1234
			else {
1235
				if (empty($page))
1236
					$page = "/";
1237
				header("Location: {$page}");
1238
			}
1239
			exit;
1240
		} else {
1241
			/* give the user an error message */
1242
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1243
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1244
			if(isAjax()) {
1245
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1246
				return;
1247
			}
1248
		}
1249
	}
1250

    
1251
	/* Show login page if they aren't logged in */
1252
	if (empty($_SESSION['Logged_In']))
1253
		return false;
1254

    
1255
	/* If session timeout isn't set, we don't mark sessions stale */
1256
	if (!isset($config['system']['webgui']['session_timeout'])) {
1257
		/* Default to 4 hour timeout if one is not set */
1258
		if ($_SESSION['last_access'] < (time() - 14400)) {
1259
			$_GET['logout'] = true;
1260
			$_SESSION['Logout'] = true;
1261
		} else
1262
			$_SESSION['last_access'] = time();	
1263
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1264
		/* only update if it wasn't ajax */
1265
		if (!isAjax())
1266
			$_SESSION['last_access'] = time();
1267
	} else {
1268
		/* Check for stale session */
1269
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1270
			$_GET['logout'] = true;
1271
			$_SESSION['Logout'] = true;
1272
		} else {
1273
			/* only update if it wasn't ajax */
1274
			if (!isAjax())
1275
				$_SESSION['last_access'] = time();
1276
		}
1277
	}
1278

    
1279
	/* user hit the logout button */
1280
	if (isset($_GET['logout'])) {
1281

    
1282
		if ($_SESSION['Logout'])
1283
			log_error("Session timed out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1284
		else
1285
			log_error("User logged out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1286

    
1287
		/* wipe out $_SESSION */
1288
		$_SESSION = array();
1289

    
1290
		if (isset($_COOKIE[session_name()]))
1291
			setcookie(session_name(), '', time()-42000, '/');
1292

    
1293
		/* and destroy it */
1294
		session_destroy();
1295

    
1296
		$scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
1297
		$scriptElms = count($scriptName);
1298
		$scriptName = $scriptName[$scriptElms-1];
1299

    
1300
		if (isAjax())
1301
			return false;
1302

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

    
1306
		return false;
1307
	}
1308

    
1309
	/*
1310
	 * this is for debugging purpose if you do not want to use Ajax
1311
	 * to submit a HTML form. It basically diables the observation
1312
	 * of the submit event and hence does not trigger Ajax.
1313
	 */
1314
	if ($_GET['disable_ajax'])
1315
		$_SESSION['NO_AJAX'] = "True";
1316

    
1317
	/*
1318
	 * Same to re-enable Ajax.
1319
	 */
1320
	if ($_GET['enable_ajax'])
1321
		unset($_SESSION['NO_AJAX']);
1322

    
1323
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1324
	return true;
1325
}
1326

    
1327
?>
(4-4/61)