Project

General

Profile

Download (40.7 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", gettext("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

    
204
	if (is_array($config['system']['user']))
205
		foreach ($config['system']['user'] as & $user)
206
			if ($user['uid'] == $uid)
207
				return $user;
208

    
209
	return false;
210
}
211

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

    
218
function & getGroupEntryByGID($gid) {
219
	global $debug, $config;
220

    
221
	if (is_array($config['system']['group']))
222
		foreach ($config['system']['group'] as & $group)
223
			if ($group['gid'] == $gid)
224
				return $group;
225

    
226
	return false;
227
}
228

    
229
function get_user_privileges(& $user) {
230

    
231
        $privs = $user['priv'];
232
        if (!is_array($privs))
233
                $privs = array();
234

    
235
        $names = local_user_get_groups($user, true);
236

    
237
        foreach ($names as $name) {
238
                $group = getGroupEntry($name);
239
                if (is_array($group['priv']))
240
                        $privs = array_merge( $privs, $group['priv']);
241
        }
242

    
243
        return $privs;
244
}
245

    
246
function userHasPrivilege($userent, $privid = false) {
247

    
248
        if (!$privid || !is_array($userent))
249
                return false;
250

    
251
        $privs = get_user_privileges($userent);
252

    
253
        if (!is_array($privs))
254
                return false;
255

    
256
        if (!in_array($privid, $privs))
257
                return false;
258

    
259
        return true;
260
}
261

    
262
function local_backed($username, $passwd) {
263

    
264
	$user = getUserEntry($username);
265
	if (!$user)
266
		return false;
267

    
268
	if (is_account_disabled($username) || is_account_expired($username))
269
		return false;
270

    
271
	if ($user['password'])
272
	{
273
		$passwd = crypt($passwd, $user['password']);
274
		if ($passwd == $user['password'])
275
			return true;
276
	}
277

    
278
	if ($user['md5-hash'])
279
	{
280
		$passwd = md5($passwd);
281
		if ($passwd == $user['md5-hash'])
282
			return true;
283
	}
284

    
285
	return false;
286
}
287

    
288
function local_sync_accounts() {
289
	global $debug, $config;
290
	conf_mount_rw();
291

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

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

    
331
	/* make sure the all group exists */
332
	$allgrp = getGroupEntryByGID(1998);
333
	local_group_set($allgrp, true);
334

    
335
	/* sync all local users */
336
	if (is_array($config['system']['user']))
337
		foreach ($config['system']['user'] as $user)
338
			local_user_set($user);
339

    
340
	/* sync all local groups */
341
	if (is_array($config['system']['group']))
342
		foreach ($config['system']['group'] as $group)
343
			local_group_set($group);
344

    
345
	conf_mount_ro();
346

    
347
}
348

    
349
function local_user_set(& $user) {
350
	global $g, $debug;
351

    
352
	conf_mount_rw();
353

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

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

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

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

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

    
400
	/* read from pw db */
401
	$fd = popen("/usr/sbin/pw usershow {$user_name} 2>&1", "r");
402
	$pwread = fgets($fd);
403
	pclose($fd);
404

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

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

    
417
	if($debug)
418
		log_error(sprintf(gettext("Running: %s"), $cmd));
419
	$fd = popen($cmd, "w");
420
	fwrite($fd, $user['password']);
421
	pclose($fd);
422

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

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

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

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

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

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

    
459
	/* delete from pw db */
460
	$cmd = "/usr/sbin/pw userdel {$user['name']} {$rmhome}";
461

    
462
	if($debug)
463
		log_error(sprintf(gettext("Running: %s"), $cmd));
464
	mwexec($cmd);
465

    
466
	/* Delete user from groups needs a call to write_config() */
467
	local_group_del_user($user);
468
}
469

    
470
function local_user_set_password(& $user, $password) {
471

    
472
	$user['password'] = crypt($password);
473
	$user['md5-hash'] = md5($password);
474

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

    
483
	// Generate the NT-HASH from the unicode string
484
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
485
}
486

    
487
function local_user_get_groups($user, $all = false) {
488
	global $debug, $config;
489

    
490
	$groups = array();
491
	if (!is_array($config['system']['group']))
492
		return $groups;
493

    
494
	foreach ($config['system']['group'] as $group)
495
		if ( $all || ( !$all && ($group['name'] != "all")))
496
			if (is_array($group['member']))
497
				if (in_array($user['uid'], $group['member']))
498
					$groups[] = $group['name'];
499

    
500
	if ( $all )
501
		$groups[] = "all";
502

    
503
	sort($groups);
504

    
505
	return $groups;
506
	
507
}
508

    
509
function local_user_set_groups($user, $new_groups = NULL ) {
510
	global $debug, $config, $groupindex;
511

    
512
	if (!is_array($config['system']['group']))
513
		return;
514

    
515
	$cur_groups = local_user_get_groups($user, true);
516
	$mod_groups = array();
517

    
518
	if (!is_array($new_groups))
519
		$new_groups = array();
520

    
521
	if (!is_array($cur_groups))
522
		$cur_groups = array();
523

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

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

    
549
	/* sync all modified groups */
550
	foreach ($mod_groups as $group)
551
		local_group_set($group);
552
}
553

    
554
function local_group_del_user($user) {
555
	global $config;
556

    
557
	if (!is_array($config['system']['group']))
558
                return;
559

    
560
        foreach ($config['system']['group'] as $group) {
561
		if (is_array($group['member'])) {
562
			foreach ($group['member'] as $idx => $uid) {
563
				if ($user['uid'] == $uid)
564
					unset($config['system']['group']['member'][$idx]);
565
			}
566
		}
567
	}
568
}
569

    
570
function local_group_set($group, $reset = false) {
571
	global $debug;
572

    
573
	$group_name = $group['name'];
574
	$group_gid = $group['gid'];
575
	$group_members = "''";
576
	if (!$reset && !empty($group['member']) && count($group['member']) > 0)
577
		$group_members = implode(",",$group['member']);
578

    
579
	/* read from group db */
580
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
581
	$pwread = fgets($fd);
582
	pclose($fd);
583

    
584
	/* determine add or mod */
585
	if (!strncmp($pwread, "pw:", 3))
586
		$group_op = "groupadd";
587
	else
588
		$group_op = "groupmod";
589

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

    
593
	if($debug)
594
		log_error(sprintf(gettext("Running: %s"), $cmd));
595
	mwexec($cmd);
596

    
597
}
598

    
599
function local_group_del($group) {
600
	global $debug;
601

    
602
	/* delete from group db */
603
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
604

    
605
	if($debug)
606
		log_error(sprintf(gettext("Running: %s"), $cmd));
607
	mwexec($cmd);
608
}
609

    
610
function ldap_test_connection($authcfg) {
611
	global $debug, $config, $g;
612

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

    
626
        /* first check if there is even an LDAP server populated */
627
        if(!$ldapserver)
628
                return false;
629

    
630
        /* Setup CA environment if needed. */
631
        ldap_setup_caenv($authcfg);
632

    
633
        /* connect and see if server is up */
634
        $error = false;
635
        if (empty($ldapport)) {
636
                if (!($ldap = ldap_connect($ldapserver)))
637
                        $error = true;
638
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
639
                $error = true;
640

    
641
        if ($error == true) {
642
                log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
643
                return false;
644
        }
645

    
646
	return true;
647
}
648

    
649
function ldap_setup_caenv($authcfg) {
650
	global $g;
651

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

    
677
function ldap_test_bind($authcfg) {
678
	global $debug, $config, $g;
679

    
680
	if ($authcfg) {
681
                if (strstr($authcfg['ldap_urltype'], "Standard"))
682
                        $ldapproto = "ldap";
683
                else
684
                        $ldapproto = "ldaps";
685
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
686
                $ldapport           = $authcfg['ldap_port'];
687
                $ldapbasedn         = $authcfg['ldap_basedn'];
688
                $ldapbindun         = $authcfg['ldap_binddn'];
689
                $ldapbindpw         = $authcfg['ldap_bindpw'];
690
                $ldapver            = $authcfg['ldap_protver'];
691
		if (empty($ldapbndun) || empty($ldapbindpw))
692
                        $ldapanon = true;
693
                else
694
                        $ldapanon = false;
695
	} else
696
		return false;
697

    
698
	/* first check if there is even an LDAP server populated */
699
        if(!$ldapserver)
700
                return false;
701

    
702
	/* Setup CA environment if needed. */
703
	ldap_setup_caenv($authcfg);
704

    
705
        /* connect and see if server is up */
706
        $error = false;
707
        if (empty($ldapport)) {
708
                if (!($ldap = ldap_connect($ldapserver)))
709
                        $error = true;
710
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
711
                $error = true;
712

    
713
        if ($error == true) {
714
                log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
715
                return false;
716
        }
717

    
718
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
719
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
720
 
721
	if ($ldapanon == true) {
722
		if (!($res = @ldap_bind($ldap))) {
723
			@ldap_close($ldap);
724
			return false;
725
		}
726
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
727
		@ldap_close($ldap);
728
		return false;
729
	}
730

    
731
	@ldap_unbind($ldap);
732

    
733
	return true;
734
}
735

    
736
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
737
	global $debug, $config, $g;
738

    
739
	if(!function_exists("ldap_connect"))
740
		return;
741

    
742
	$ous = array();
743

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

    
765
        /* first check if there is even an LDAP server populated */
766
        if(!$ldapserver) {
767
                log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
768
                return $ous;
769
        }
770

    
771
	/* Setup CA environment if needed. */
772
	ldap_setup_caenv($authcfg);
773

    
774
	/* connect and see if server is up */
775
        $error = false;
776
        if (empty($ldapport)) {
777
                if (!($ldap = ldap_connect($ldapserver)))
778
                        $error = true;
779
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
780
                $error = true;
781

    
782
        if ($error == true) {
783
        log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
784
                return $ous;
785
        }
786

    
787
	$ldapfilter = "(|(ou=*)(cn=Users))";
788

    
789
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
790
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
791

    
792
	if ($ldapanon == true) {
793
                if (!($res = @ldap_bind($ldap))) {
794
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
795
			@ldap_close($ldap);
796
                        return $ous;
797
		}
798
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
799
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
800
		@ldap_close($ldap);
801
		return $ous;
802
	}
803

    
804
	if ($ldapscope == "one")
805
		$ldapfunc = "ldap_list";
806
	else
807
		$ldapfunc = "ldap_search";
808

    
809
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
810
	$info = @ldap_get_entries($ldap, $search);
811

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

    
827
	@ldap_unbind($ldap);
828

    
829
	return $ous;
830
}
831

    
832
function ldap_get_groups($username, $authcfg) {
833
	global $debug, $config;
834
	
835
	if(!function_exists("ldap_connect"))
836
		return;
837
	
838
	if(!$username) 
839
		return false;
840

    
841
	if(stristr($username, "@")) {
842
		$username_split=split("\@", $username);
843
		$username = $username_split[0];		
844
	}
845

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

    
878
	$ldapdn             = $_SESSION['ldapdn'];
879

    
880
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
881
	$ldapgroupattribute = strtolower($ldapgroupattribute);
882
	$memberof = array();
883

    
884
        /* Setup CA environment if needed. */
885
        ldap_setup_caenv($authcfg);
886

    
887
	/* connect and see if server is up */
888
	$error = false;
889
        if (empty($ldapport)) {
890
                if (!($ldap = ldap_connect($ldapserver)))
891
                        $error = true;
892
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
893
                $error = true;
894

    
895
	if ($error == true) {
896
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
897
                return memberof;
898
        }
899
    
900
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
901
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
902

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

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

    
925
	$search    = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
926
	$info      = @ldap_get_entries($ldap, $search);
927

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

    
950
function ldap_backed($username, $passwd, $authcfg) {
951
	global $debug, $config;
952
	
953
	if(!$username) 
954
		return;
955

    
956
	if(!function_exists("ldap_connect"))
957
		return;
958

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

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

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

    
1000
		return false;
1001
	}
1002
	
1003
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1004
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1005

    
1006
        /* Setup CA environment if needed. */
1007
        ldap_setup_caenv($authcfg);
1008

    
1009
	/* Make sure we can connect to LDAP */
1010
	$error = false;
1011
	if (empty($ldapport)) {
1012
		if (!($ldap = ldap_connect($ldapserver)))
1013
			$error = true;
1014
	} else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
1015
		$error = true;
1016

    
1017
	if ($error == true) {
1018
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1019
		return false;
1020
	}
1021

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

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

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

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

    
1084
	/* Now lets bind as the user we found */
1085
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1086
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s.'), $ldapname, $username));
1087
		@ldap_unbind($ldap);
1088
		return false;
1089
	}
1090

    
1091
	log_error(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1092

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

    
1096
	return true;
1097
}
1098

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

    
1103
	require_once("radius.inc");
1104

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

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

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

    
1125
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1126

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

    
1145
	// close OO RADIUS_AUTHENTICATION
1146
	$rauth->close();
1147

    
1148
	return $ret;
1149
}
1150

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

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

    
1164
	return false;
1165
}
1166

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

    
1172
	return false;
1173
}
1174

    
1175
function auth_get_authserver($name) {
1176
        global $config;
1177

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

    
1188
function auth_get_authserver_list() {
1189
        global $config;
1190

    
1191
	$list = array();
1192

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

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

    
1204
function getUserGroups($username, $authcfg) {
1205
	global $config;
1206

    
1207
	$allowed_groups = array();
1208

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

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

    
1228
	return $member_groups;
1229
}
1230

    
1231
function authenticate_user($username, $password, $authcfg = NULL) {
1232

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

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

    
1254
	return $authenticated;
1255
}
1256

    
1257
function session_auth() {
1258
	global $HTTP_SERVER_VARS, $config, $_SESSION, $page;
1259

    
1260
	session_start();
1261

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

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

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

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

    
1324
		if ($_SESSION['Logout'])
1325
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1326
		else
1327
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1328

    
1329
		/* wipe out $_SESSION */
1330
		$_SESSION = array();
1331

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

    
1335
		/* and destroy it */
1336
		session_destroy();
1337

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

    
1342
		if (isAjax())
1343
			return false;
1344

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

    
1348
		return false;
1349
	}
1350

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

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

    
1365
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1366
	return true;
1367
}
1368

    
1369
?>
(4-4/61)