Project

General

Profile

Download (38.4 KB) Statistics
| Branch: | Tag: | Revision:
1 55eb9c44 --global
<?php
2
/* $Id$ */
3
/*
4 8a6b0fbe Ermal Lu?i
	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 55eb9c44 --global
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 523855b0 Scott Ullrich
		pfSense_BUILDER_BINARIES:	/usr/sbin/pw	/bin/cp
42
		pfSense_MODULE:	auth
43 55eb9c44 --global
*/
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 052e65ef Scott Ullrich
if(!$do_not_include_config_gui_inc)
50
	require_once("config.gui.inc");
51 55eb9c44 --global
52 9ae11a62 Scott Ullrich
// Will be changed to false if security checks fail
53
$security_passed = true;
54
55 0321fa1b jim-p
/* 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 14eab6fb jim-p
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
58 0321fa1b jim-p
	/* DNS ReBinding attack prevention.  http://redmine.pfsense.org/issues/708 */
59
	$found_host = false;
60 7319dc73 jim-p
	if(strstr($_SERVER['HTTP_HOST'], ":")) {
61
		$http_host_port = explode(":", $_SERVER['HTTP_HOST']);
62
		$http_host = $http_host_port[0];
63
	} else {
64
		$http_host = $_SERVER['HTTP_HOST'];
65
	}
66 f17f9f28 jim-p
	if(is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
67 9ae11a62 Scott Ullrich
			strcasecmp($http_host, "localhost") == 0)
68
		$found_host = true;
69
	if(strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
70
			strcasecmp($http_host, $config['system']['hostname']) == 0)
71 d7bf3178 Erik Fonnesbeck
		$found_host = true;
72 9ae11a62 Scott Ullrich
73
	if(is_array($config['dyndnses']['dyndns']) && !$found_host)
74 0321fa1b jim-p
		foreach($config['dyndnses']['dyndns'] as $dyndns)
75 9ae11a62 Scott Ullrich
			if(strcasecmp($dyndns['host'], $http_host) == 0) {
76 0321fa1b jim-p
				$found_host = true;
77 9ae11a62 Scott Ullrich
				break;
78
			}
79 7319dc73 jim-p
80 9ae11a62 Scott Ullrich
	if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
81 86b21903 jim-p
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
82
		foreach ($althosts as $ah)
83 9ae11a62 Scott Ullrich
			if(strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
84 86b21903 jim-p
				$found_host = true;
85 9ae11a62 Scott Ullrich
				break;
86
			}
87 9b13f84b Scott Ullrich
	}
88 ce46b5da Scott Ullrich
89 9ae11a62 Scott Ullrich
	if($found_host == false) {
90
		if(!security_checks_disabled()) {
91
			display_error_form("501", "Potential DNS Rebind attack detected, see http://en.wikipedia.org/wiki/DNS_rebinding<br/>Try accessing the router by IP address instead of by hostname.");
92
			exit;
93
		}
94
		$security_passed = false;
95
	}
96
}
97 ef173724 Scott Ullrich
98 9ae11a62 Scott Ullrich
// If the HTTP_REFERER is something other than ourselves then disallow.
99
if(function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
100
	if($_SERVER['HTTP_REFERER']) {
101
		if(file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
102
			if($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
103
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
104
				header("Refresh: 1; url=index.php");
105
				echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
106
				echo "<html><head><title>" . gettext("Redirecting...") . "</title></head><body>" . gettext("Redirecting to the dashboard...") . "</body></html>";
107
				exit;
108
			}
109
		}
110
		$found_host = false;
111
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
112
		if($referrer_host) {
113
			if(strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0
114
					|| strcasecmp($referrer_host, $config['system']['hostname']) == 0)
115
				$found_host = true;
116
			if(!empty($config['system']['webgui']['althostnames']) && !$found_host) {
117
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
118
				foreach ($althosts as $ah) {
119
					if(strcasecmp($referrer_host, $ah) == 0) {
120
						$found_host = true;
121
						break;
122
					}
123
				}
124
			}
125
			if(!$found_host) {
126
				$interface_list_ips = get_configured_ip_addresses();
127
				foreach($interface_list_ips as $ilips) {
128
					if(strcasecmp($referrer_host, $ilips) == 0) {
129
						$found_host = true;
130
						break;
131
					}
132
				}
133 17dd7ff3 Chris Buechler
				if($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
134
					// allow SSH port forwarded connections and links from localhost
135
					$found_host = true;
136
				}
137 9ae11a62 Scott Ullrich
			}
138
		}
139 4fe9c2dc Scott Ullrich
		if($found_host == false) {
140 9ae11a62 Scott Ullrich
			if(!security_checks_disabled()) {
141
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  You can disable this check if needed in System -> Advanced -> Admin.");
142 0f806eca Erik Fonnesbeck
				exit;
143
			}
144 9ae11a62 Scott Ullrich
			$security_passed = false;
145
		}
146
	} else
147
		$security_passed = false;
148 4fe9c2dc Scott Ullrich
}
149
150 9ae11a62 Scott Ullrich
if (function_exists("display_error_form") && $security_passed)
151
	/* Security checks passed, so it should be OK to turn them back on */
152
	restore_security_checks();
153
unset($security_passed);
154
155 55eb9c44 --global
$groupindex = index_groups();
156
$userindex = index_users();
157
158
function index_groups() {
159
	global $g, $debug, $config, $groupindex;
160
161
	$groupindex = array();
162
163 6dcd80af Ermal
	if (is_array($config['system']['group'])) {
164 55eb9c44 --global
		$i = 0;
165
		foreach($config['system']['group'] as $groupent) {
166
			$groupindex[$groupent['name']] = $i;
167
			$i++;
168
		}
169
	}
170
171
	return ($groupindex);
172
}
173
174
function index_users() {
175
	global $g, $debug, $config;
176
177 6dcd80af Ermal
	if (is_array($config['system']['user'])) {
178 55eb9c44 --global
		$i = 0;
179
		foreach($config['system']['user'] as $userent) {
180
			$userindex[$userent['name']] = $i;
181
			$i++;
182
		}
183
	}
184
185
	return ($userindex);
186
}
187
188
function & getUserEntry($name) {
189
	global $debug, $config, $userindex;
190
	if (isset($userindex[$name]))
191
		return $config['system']['user'][$userindex[$name]];
192
}
193
194
function & getUserEntryByUID($uid) {
195
	global $debug, $config;
196
	foreach ($config['system']['user'] as & $user)
197
		if ($user['uid'] == $uid)
198
			return $user;
199
200
	return false;
201
}
202
203
function & getGroupEntry($name) {
204
	global $debug, $config, $groupindex;
205
	if (isset($groupindex[$name]))
206
		return $config['system']['group'][$groupindex[$name]];
207
}
208
209
function & getGroupEntryByGID($gid) {
210
	global $debug, $config;
211
	foreach ($config['system']['group'] as & $group)
212
		if ($group['gid'] == $gid)
213
			return $group;
214
215
	return false;
216
}
217
218 6dc88d53 Ermal Luci
function get_user_privileges(& $user) {
219
220
        $privs = $user['priv'];
221
        if (!is_array($privs))
222
                $privs = array();
223
224
        $names = local_user_get_groups($user, true);
225
226
        foreach ($names as $name) {
227
                $group = getGroupEntry($name);
228
                if (is_array($group['priv']))
229
                        $privs = array_merge( $privs, $group['priv']);
230
        }
231
232
        return $privs;
233
}
234
235
function userHasPrivilege($userent, $privid = false) {
236
237
        if (!$privid || !is_array($userent))
238
                return false;
239
240
        $privs = get_user_privileges($userent);
241
242
        if (!is_array($privs))
243
                return false;
244
245
        if (!in_array($privid, $privs))
246
                return false;
247
248
        return true;
249
}
250
251 55eb9c44 --global
function local_backed($username, $passwd) {
252
253
	$user = getUserEntry($username);
254
	if (!$user)
255
		return false;
256
257 6306b5dd Ermal Lu?i
	if (is_account_disabled($username) || is_account_expired($username))
258 a13ce628 Ermal Lu?i
		return false;
259
260 55eb9c44 --global
	if ($user['password'])
261
	{
262
		$passwd = crypt($passwd, $user['password']);
263
		if ($passwd == $user['password'])
264
			return true;
265
	}
266
267
	if ($user['md5-hash'])
268
	{
269
		$passwd = md5($passwd);
270
		if ($passwd == $user['md5-hash'])
271
			return true;
272
	}
273
274
	return false;
275
}
276
277
function local_sync_accounts() {
278
	global $debug, $config;
279
	conf_mount_rw();
280
281
	/* remove local users to avoid uid conflicts */
282
	$fd = popen("/usr/sbin/pw usershow -a", "r");
283
	if ($fd) {
284
		while (!feof($fd)) {
285
			$line = explode(":",fgets($fd));
286
			if (!strncmp($line[0], "_", 1))
287
				continue;
288
			if ($line[2] < 2000)
289
				continue;
290
			if ($line[2] > 65000)
291
				continue;
292
			$cmd = "/usr/sbin/pw userdel {$line[2]}";
293
			if($debug)
294
				log_error("Running: {$cmd}");
295
			mwexec($cmd);
296
		}
297
		pclose($fd);
298
	}
299
300
	/* remove local groups to avoid gid conflicts */
301
	$gids = array();
302
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
303
	if ($fd) {
304
		while (!feof($fd)) {
305
			$line = explode(":",fgets($fd));
306
			if (!strncmp($line[0], "_", 1))
307
				continue;
308
			if ($line[2] < 2000)
309
				continue;
310
			if ($line[2] > 65000)
311
				continue;
312
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
313
			if($debug)
314
				log_error("Running: {$cmd}");
315
			mwexec($cmd);
316
		}
317
		pclose($fd);
318
	}
319
320
	/* make sure the all group exists */
321
	$allgrp = getGroupEntryByGID(1998);
322
	local_group_set($allgrp, true);
323
324 5af2baf7 jim-p
	/* sync all local users */
325
	if (is_array($config['system']['user']))
326
		foreach ($config['system']['user'] as $user)
327
			local_user_set($user);
328
329 f3e0a111 jim-p
	/* sync all local groups */
330
	if (is_array($config['system']['group']))
331
		foreach ($config['system']['group'] as $group)
332
			local_group_set($group);
333
334 55eb9c44 --global
	conf_mount_ro();
335
336
}
337
338
function local_user_set(& $user) {
339
	global $g, $debug;
340
341 2bb07efc Scott Ullrich
	conf_mount_rw();
342
343 55eb9c44 --global
	$home_base = "/home/";	
344
	$user_uid = $user['uid'];
345
	$user_name = $user['name'];
346 461df7c0 jim-p
	$user_home = "{$home_base}{$user_name}";
347 55eb9c44 --global
	$user_shell = "/etc/rc.initial";
348
	$user_group = "nobody";
349
350
	// Ensure $home_base exists and is writable
351
	if (!is_dir($home_base)) 
352
		mkdir($home_base, 0755);
353
354 df8d74de jim-p
	$lock_account = false;
355 55eb9c44 --global
	/* configure shell type */
356 3e251b12 Erik Fonnesbeck
	/* Cases here should be ordered by most privileged to least privileged. */
357 a137fedd jim-p
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
358 29293dce jim-p
		$user_shell = "/bin/tcsh";
359 1ed86bc6 jim-p
	} elseif (userHasPrivilege($user, "user-copy-files")) {
360 a137fedd jim-p
		$user_shell = "/usr/local/bin/scponly";
361 3e251b12 Erik Fonnesbeck
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
362
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
363 fbfd675a jim-p
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
364
		$user_shell = "/sbin/nologin";
365 1ed86bc6 jim-p
	} else {
366
		$user_shell = "/sbin/nologin";
367 df8d74de jim-p
		$lock_account = true;
368
	}
369
370
	/* Lock out disabled or expired users, unless it's root/admin. */
371
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
372
		$user_shell = "/sbin/nologin";
373
		$lock_account = true;
374 55eb9c44 --global
	}
375
376
	/* root user special handling */
377
	if ($user_uid == 0) {
378
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
379
		if($debug)
380
			log_error("Running: {$cmd}");
381
		$fd = popen($cmd, "w");
382
		fwrite($fd, $user['password']);
383
		pclose($fd);
384
		$user_group = "wheel";
385 2708e399 jim-p
		$user_home = "/root";
386 29293dce jim-p
		$user_shell = "/etc/rc.initial";
387 55eb9c44 --global
	}
388
389
	/* read from pw db */
390
	$fd = popen("/usr/sbin/pw usershow {$user_name} 2>&1", "r");
391
	$pwread = fgets($fd);
392
	pclose($fd);
393
394
	/* determine add or mod */
395 38564fde smos
	if (!strncmp($pwread, "pw:", 3)) {
396 4b49a8a9 jim-p
		$user_op = "useradd -m -k /etc/skel -o";
397 38564fde smos
	} else {
398 55eb9c44 --global
		$user_op = "usermod";
399 38564fde smos
	}
400 55eb9c44 --global
401
	/* add or mod pw db */
402
	$cmd = "/usr/sbin/pw {$user_op} -q -u {$user_uid} -n {$user_name}".
403 eb72845c jim-p
			" -g {$user_group} -s {$user_shell} -d {$user_home}".
404 9ff73b79 jim-p
			" -c ".escapeshellarg($user['descr'])." -H 0 2>&1";
405 55eb9c44 --global
406
	if($debug)
407
		log_error("Running: {$cmd}");
408
	$fd = popen($cmd, "w");
409
	fwrite($fd, $user['password']);
410
	pclose($fd);
411
412
	/* create user directory if required */
413
	if (!is_dir($user_home)) {
414
		mkdir($user_home, 0700);
415 ee4fc984 Ermal
		mwexec("/bin/cp /root/.* {$home_base}/", true);
416 55eb9c44 --global
	}
417
	chown($user_home, $user_name);
418
	chgrp($user_home, $user_group);
419
420
	/* write out ssh authorized key file */
421
	if($user['authorizedkeys']) {
422 a2286360 Ermal Lu?i
		if (!is_dir("{$user_home}/.ssh")) {
423
			mkdir("{$user_home}/.ssh", 0700);
424
			chown("{$user_home}/.ssh", $user_name);
425
		}
426
		$keys = base64_decode($user['authorizedkeys']);
427
		file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
428
		chown("{$user_home}/.ssh/authorized_keys", $user_name);
429 cdab65cc Erik Fonnesbeck
	} else
430
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
431 df8d74de jim-p
432
	$un = $lock_account ? "" : "un";
433 7ac98d0b Erik Fonnesbeck
	exec("/usr/sbin/pw {$un}lock {$user_name} -q");
434 2bb07efc Scott Ullrich
	
435
	conf_mount_ro();
436 55eb9c44 --global
}
437
438
function local_user_del($user) {
439
	global $debug;
440 2bb07efc Scott Ullrich
441 55eb9c44 --global
	/* remove all memberships */
442 019e6c3f jim-p
	local_user_set_groups($user);
443 55eb9c44 --global
444 a39675ec jim-p
	/* Don't remove /root */
445
	if ($user['uid'] != 0)
446
		$rmhome = "-r";
447
448 55eb9c44 --global
	/* delete from pw db */
449 a39675ec jim-p
	$cmd = "/usr/sbin/pw userdel {$user['name']} {$rmhome}";
450 55eb9c44 --global
451
	if($debug)
452
		log_error("Running: {$cmd}");
453 0914b6bb Ermal
	mwexec($cmd);
454 2bb07efc Scott Ullrich
455 0914b6bb Ermal
	/* Delete user from groups needs a call to write_config() */
456
	local_group_del_user($user);
457 55eb9c44 --global
}
458
459
function local_user_set_password(& $user, $password) {
460
461
	$user['password'] = crypt($password);
462
	$user['md5-hash'] = md5($password);
463
464
	// Converts ascii to unicode.
465
	$astr = (string) $password;
466
	$ustr = '';
467
	for ($i = 0; $i < strlen($astr); $i++) {
468
		$a = ord($astr{$i}) << 8;
469
		$ustr.= sprintf("%X", $a);
470
	}
471
472
	// Generate the NT-HASH from the unicode string
473
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
474
}
475
476
function local_user_get_groups($user, $all = false) {
477
	global $debug, $config;
478
479
	$groups = array();
480
	if (!is_array($config['system']['group']))
481
		return $groups;
482
483
	foreach ($config['system']['group'] as $group)
484
		if ( $all || ( !$all && ($group['name'] != "all")))
485
			if (is_array($group['member']))
486
				if (in_array($user['uid'], $group['member']))
487
					$groups[] = $group['name'];
488
489 b0c231e4 jim-p
	if ( $all )
490
		$groups[] = "all";
491
492 55eb9c44 --global
	sort($groups);
493
494
	return $groups;
495
	
496
}
497
498
function local_user_set_groups($user, $new_groups = NULL ) {
499
	global $debug, $config, $groupindex;
500
501
	if (!is_array($config['system']['group']))
502
		return;
503
504 739c78ac jim-p
	$cur_groups = local_user_get_groups($user, true);
505 55eb9c44 --global
	$mod_groups = array();
506
507
	if (!is_array($new_groups))
508
		$new_groups = array();
509
510
	if (!is_array($cur_groups))
511
		$cur_groups = array();
512
513
	/* determine which memberships to add */
514
	foreach ($new_groups as $groupname) {
515
		if (in_array($groupname,$cur_groups))
516
			continue;
517
		$group = & $config['system']['group'][$groupindex[$groupname]];
518
		$group['member'][] = $user['uid'];
519
		$mod_groups[] = $group;
520
	}
521 9ae11a62 Scott Ullrich
	unset($group);
522 55eb9c44 --global
523
	/* determine which memberships to remove */
524
	foreach ($cur_groups as $groupname) {
525
		if (in_array($groupname,$new_groups))
526 e879fc81 Ermal
			continue;
527 25fec9b3 jim-p
		if (!isset($config['system']['group'][$groupindex[$groupname]]))
528
			continue;
529 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
530 7b5c56ea jim-p
		if (is_array($group['member'])) {
531
			$index = array_search($user['uid'], $group['member']);
532
			array_splice($group['member'], $index, 1);
533
			$mod_groups[] = $group;
534
		}
535 55eb9c44 --global
	}
536 9ae11a62 Scott Ullrich
	unset($group);
537 55eb9c44 --global
538
	/* sync all modified groups */
539
	foreach ($mod_groups as $group)
540
		local_group_set($group);
541
}
542
543 0914b6bb Ermal
function local_group_del_user($user) {
544
	global $config;
545
546
	if (!is_array($config['system']['group']))
547
                return;
548
549
        foreach ($config['system']['group'] as $group) {
550
		if (is_array($group['member'])) {
551
			foreach ($group['member'] as $idx => $uid) {
552
				if ($user['uid'] == $uid)
553
					unset($config['system']['group']['member'][$idx]);
554
			}
555
		}
556
	}
557
}
558
559 55eb9c44 --global
function local_group_set($group, $reset = false) {
560
	global $debug;
561
562
	$group_name = $group['name'];
563
	$group_gid = $group['gid'];
564
	$group_members = "''";
565 cbe49517 Ermal
	if (!$reset && !empty($group['member']) && count($group['member']) > 0)
566 55eb9c44 --global
		$group_members = implode(",",$group['member']);
567
568
	/* read from group db */
569
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
570
	$pwread = fgets($fd);
571
	pclose($fd);
572
573
	/* determine add or mod */
574
	if (!strncmp($pwread, "pw:", 3))
575
		$group_op = "groupadd";
576
	else
577
		$group_op = "groupmod";
578
579
	/* add or mod group db */
580
	$cmd = "/usr/sbin/pw {$group_op} {$group_name} -g {$group_gid} -M {$group_members} 2>&1";
581
582
	if($debug)
583
		log_error("Running: {$cmd}");
584 0914b6bb Ermal
	mwexec($cmd);
585 55eb9c44 --global
586
}
587
588
function local_group_del($group) {
589
	global $debug;
590
591
	/* delete from group db */
592
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
593
594
	if($debug)
595
		log_error("Running: {$cmd}");
596 0914b6bb Ermal
	mwexec($cmd);
597 55eb9c44 --global
}
598
599 6306b5dd Ermal Lu?i
function ldap_test_connection($authcfg) {
600 55eb9c44 --global
	global $debug, $config, $g;
601
602 c61e4626 Ermal Lu?i
	if ($authcfg) {
603
                if (strstr($authcfg['ldap_urltype'], "Standard"))
604
                        $ldapproto = "ldap";
605
                else
606
                        $ldapproto = "ldaps";
607
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
608
                $ldapport           = $authcfg['ldap_port'];
609
                $ldapbasedn         = $authcfg['ldap_basedn'];
610
                $ldapbindun         = $authcfg['ldap_binddn'];
611
                $ldapbindpw         = $authcfg['ldap_bindpw'];
612 6306b5dd Ermal Lu?i
        } else
613
		return false;
614 55eb9c44 --global
615 c61e4626 Ermal Lu?i
        /* first check if there is even an LDAP server populated */
616
        if(!$ldapserver)
617
                return false;
618
619
        /* connect and see if server is up */
620
        putenv('LDAPTLS_REQCERT=never');
621
        $error = false;
622
        if (empty($ldapport)) {
623
                if (!($ldap = ldap_connect($ldapserver)))
624
                        $error = true;
625
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
626
                $error = true;
627
628
        if ($error == true) {
629
                log_error("ERROR!  Could not connect to server {$ldapname}.");
630
                return false;
631
        }
632 55eb9c44 --global
633
	return true;
634
}
635
636 6306b5dd Ermal Lu?i
function ldap_test_bind($authcfg) {
637 55eb9c44 --global
	global $debug, $config, $g;
638
639 c61e4626 Ermal Lu?i
	if ($authcfg) {
640
                if (strstr($authcfg['ldap_urltype'], "Standard"))
641
                        $ldapproto = "ldap";
642
                else
643
                        $ldapproto = "ldaps";
644
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
645
                $ldapport           = $authcfg['ldap_port'];
646
                $ldapbasedn         = $authcfg['ldap_basedn'];
647
                $ldapbindun         = $authcfg['ldap_binddn'];
648
                $ldapbindpw         = $authcfg['ldap_bindpw'];
649
                $ldapver            = $authcfg['ldap_protver'];
650
		if (empty($ldapbndun) || empty($ldapbindpw))
651
                        $ldapanon = true;
652
                else
653
                        $ldapanon = false;
654 6306b5dd Ermal Lu?i
	} else
655
		return false;
656 c61e4626 Ermal Lu?i
657
	/* first check if there is even an LDAP server populated */
658
        if(!$ldapserver)
659
                return false;
660
661
        /* connect and see if server is up */
662
        putenv('LDAPTLS_REQCERT=never');
663
        $error = false;
664
        if (empty($ldapport)) {
665
                if (!($ldap = ldap_connect($ldapserver)))
666
                        $error = true;
667
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
668
                $error = true;
669
670
        if ($error == true) {
671
                log_error("ERROR!  Could not connect to server {$ldapname}.");
672
                return false;
673
        }
674 55eb9c44 --global
675
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
676 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
677
 
678
	if ($ldapanon == true) {
679 6306b5dd Ermal Lu?i
		if (!($res = @ldap_bind($ldap))) {
680
			@ldap_close($ldap);
681 c61e4626 Ermal Lu?i
			return false;
682 6306b5dd Ermal Lu?i
		}
683
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
684
		@ldap_close($ldap);
685 55eb9c44 --global
		return false;
686 6306b5dd Ermal Lu?i
	}
687 55eb9c44 --global
688 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
689 c61e4626 Ermal Lu?i
690 55eb9c44 --global
	return true;
691
}
692
693 6306b5dd Ermal Lu?i
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
694 55eb9c44 --global
	global $debug, $config, $g;
695
696
	if(!function_exists("ldap_connect"))
697
		return;
698
699 7a938f1b Ermal
	$ous = array();
700
701 c61e4626 Ermal Lu?i
	if ($authcfg) {
702
                if (strstr($authcfg['ldap_urltype'], "Standard"))
703
                        $ldapproto = "ldap";
704
                else
705
                        $ldapproto = "ldaps";
706
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
707
                $ldapport           = $authcfg['ldap_port'];
708
                $ldapbasedn         = $authcfg['ldap_basedn'];
709
                $ldapbindun         = $authcfg['ldap_binddn'];
710
                $ldapbindpw         = $authcfg['ldap_bindpw'];
711
                $ldapver            = $authcfg['ldap_protver'];
712
		if (empty($ldapbindun) || empty($ldapbindpw))
713
                        $ldapanon = true;
714
                else
715
                        $ldapanon = false;
716
                $ldapname           = $authcfg['name'];
717
                $ldapfallback       = false;
718
		$ldapscope          = $authcfg['ldap_scope'];
719 6306b5dd Ermal Lu?i
        } else
720
		return false;
721 55eb9c44 --global
722 c61e4626 Ermal Lu?i
        /* first check if there is even an LDAP server populated */
723
        if(!$ldapserver) {
724
                log_error("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined.");
725
                return $ous;
726
        }
727
728
	/* connect and see if server is up */
729
        putenv('LDAPTLS_REQCERT=never');
730
        $error = false;
731
        if (empty($ldapport)) {
732
                if (!($ldap = ldap_connect($ldapserver)))
733
                        $error = true;
734
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
735
                $error = true;
736
737
        if ($error == true) {
738
		log_error("ERROR!  Could not connect to server {$ldapname}.");
739
                return $ous;
740
        }
741
742
	$ldapfilter = "(|(ou=*)(cn=Users))";
743 55eb9c44 --global
744
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
745 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
746 55eb9c44 --global
747 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
748
                if (!($res = @ldap_bind($ldap))) {
749 6306b5dd Ermal Lu?i
			log_error("ERROR! ldap_get_user_ous() could not bind anonymously to server {$ldapname}.");
750
			@ldap_close($ldap);
751 c61e4626 Ermal Lu?i
                        return $ous;
752
		}
753
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
754
		log_error("ERROR! ldap_get_user_ous() could not bind to server {$ldapname}.");
755 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
756 c61e4626 Ermal Lu?i
		return $ous;
757 55eb9c44 --global
	}
758
759 c61e4626 Ermal Lu?i
	if ($ldapscope == "one")
760
		$ldapfunc = "ldap_list";
761
	else
762
		$ldapfunc = "ldap_search";
763 55eb9c44 --global
764 7a938f1b Ermal
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
765
	$info = @ldap_get_entries($ldap, $search);
766 55eb9c44 --global
767
	if (is_array($info)) {
768
		foreach ($info as $inf) {
769
			if (!$show_complete_ou) {
770
				$inf_split = split(",", $inf['dn']);
771
				$ou = $inf_split[0];
772
				$ou = str_replace("OU=","", $ou);
773 c61e4626 Ermal Lu?i
				$ou = str_replace("CN=","", $ou);
774 55eb9c44 --global
			} else
775
				if($inf['dn'])
776
					$ou = $inf['dn'];
777
			if($ou)
778
				$ous[] = $ou;
779
		}
780
	}
781
782 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
783
784 55eb9c44 --global
	return $ous;
785
}
786
787 6306b5dd Ermal Lu?i
function ldap_get_groups($username, $authcfg) {
788 55eb9c44 --global
	global $debug, $config;
789
	
790
	if(!function_exists("ldap_connect"))
791
		return;
792
	
793
	if(!$username) 
794
		return false;
795
796
	if(stristr($username, "@")) {
797
		$username_split=split("\@", $username);
798
		$username = $username_split[0];		
799
	}
800
801
	if(stristr($username, "\\")) {
802
		$username_split=split("\\", $username);
803
		$username = $username_split[0];        
804
	}    
805
	
806
	//log_error("Getting LDAP groups for {$username}.");
807 c61e4626 Ermal Lu?i
        if ($authcfg) {
808
                if (strstr($authcfg['ldap_urltype'], "Standard"))
809
                        $ldapproto = "ldap";
810
                else
811
                        $ldapproto = "ldaps";
812
                $ldapserver         = "{$ldapproto}://{$authcfg['host']}";
813
                $ldapport           = $authcfg['ldap_port'];
814
                $ldapbasedn         = $authcfg['ldap_basedn'];
815
                $ldapbindun         = $authcfg['ldap_binddn'];
816
                $ldapbindpw         = $authcfg['ldap_bindpw'];
817
                $ldapauthcont       = $authcfg['ldap_authcn'];
818
                $ldapnameattribute  = strtolower($authcfg['ldap_attr_user']);
819
                $ldapgroupattribute  = strtolower($authcfg['ldap_attr_member']);
820
                $ldapfilter         = "({$ldapnameattribute}={$username})";
821
                $ldaptype           = "";
822
                $ldapver            = $authcfg['ldap_protver'];
823
		if (empty($ldapbindun) || empty($ldapbindpw))
824
                        $ldapanon = true;
825
                else
826
                        $ldapanon = false;
827
                $ldapname           = $authcfg['name'];
828
                $ldapfallback       = false;
829
		$ldapscope          = $authcfg['ldap_scope'];
830 6306b5dd Ermal Lu?i
	} else
831
		return false;
832 c61e4626 Ermal Lu?i
833 55eb9c44 --global
	$ldapdn             = $_SESSION['ldapdn'];
834 c61e4626 Ermal Lu?i
835 55eb9c44 --global
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
836
	$ldapgroupattribute = strtolower($ldapgroupattribute);
837 c61e4626 Ermal Lu?i
	$memberof = array();
838 55eb9c44 --global
839
	/* connect and see if server is up */
840
	putenv('LDAPTLS_REQCERT=never');
841 c61e4626 Ermal Lu?i
	$error = false;
842
        if (empty($ldapport)) {
843
                if (!($ldap = ldap_connect($ldapserver)))
844
                        $error = true;
845
        } else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
846
                $error = true;
847
848
	if ($error == true) {
849
		log_error("ERROR! ldap_get_groups() Could not connect to server {$ldapname}.");
850
                return memberof;
851
        }
852 55eb9c44 --global
    
853
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
854 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
855 55eb9c44 --global
856
	/* bind as user that has rights to read group attributes */
857 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
858 6306b5dd Ermal Lu?i
                if (!($res = @ldap_bind($ldap))) {
859
			log_error("ERROR! ldap_get_groups() could not bind anonymously to server {$ldapname}.");
860
			@ldap_close($ldap);
861 c61e4626 Ermal Lu?i
                        return false;
862 6306b5dd Ermal Lu?i
		}
863 c61e4626 Ermal Lu?i
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
864
		log_error("ERROR! ldap_get_groups() could not bind to server {$ldapname}.");
865 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
866 c61e4626 Ermal Lu?i
		return memberof;
867 55eb9c44 --global
	}
868
869
	/* get groups from DN found */
870
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
871
	/* since we know the DN is in $_SESSION['ldapdn'] */
872
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
873 c61e4626 Ermal Lu?i
	if ($ldapscope == "one")
874
                $ldapfunc = "ldap_list";
875
        else
876
                $ldapfunc = "ldap_search";
877
878 7a938f1b Ermal
	$search    = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
879
	$info      = @ldap_get_entries($ldap, $search);
880 55eb9c44 --global
881
	$countem = $info["count"];	
882
	
883
	if(is_array($info[0][$ldapgroupattribute])) {
884
		/* Iterate through the groups and throw them into an array */
885
		foreach ($info[0][$ldapgroupattribute] as $member) {
886
			if (stristr($member, "CN=") !== false) {
887
				$membersplit = split(",", $member);
888
				$memberof[] = preg_replace("/CN=/i", "", $membersplit[0]);
889
			}
890
		}
891
	}
892
	
893
	/* Time to close LDAP connection */
894 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
895 55eb9c44 --global
	
896
	$groups = print_r($memberof,true);
897
	
898
	//log_error("Returning groups ".$groups." for user $username");
899
	
900
	return $memberof;
901
}
902
903 6306b5dd Ermal Lu?i
function ldap_backed($username, $passwd, $authcfg) {
904 55eb9c44 --global
	global $debug, $config;
905
	
906
	if(!$username) 
907
		return;
908
909
	if(!function_exists("ldap_connect"))
910
		return;
911
912
	if(stristr($username, "@")) {
913
		$username_split=split("\@", $username);
914
		$username = $username_split[0];        
915
	}
916
	if(stristr($username, "\\")) {
917
		$username_split=split("\\", $username);
918
		$username = $username_split[0];        
919
	}
920
921 c61e4626 Ermal Lu?i
	if ($authcfg) {
922
		if (strstr($authcfg['ldap_urltype'], "Standard"))
923
			$ldapproto = "ldap";
924
		else
925
			$ldapproto = "ldaps";
926
		$ldapserver         = "{$ldapproto}://{$authcfg['host']}";
927
		$ldapport	    = $authcfg['ldap_port'];
928
                $ldapbasedn         = $authcfg['ldap_basedn'];
929
                $ldapbindun         = $authcfg['ldap_binddn'];
930
                $ldapbindpw         = $authcfg['ldap_bindpw'];
931
		if (empty($ldapbindun) || empty($ldapbindpw))
932
			$ldapanon = true;
933
		else
934
			$ldapanon = false;
935
                $ldapauthcont       = $authcfg['ldap_authcn'];
936
                $ldapnameattribute  = strtolower($authcfg['ldap_attr_user']);
937
                $ldapfilter         = "({$ldapnameattribute}={$username})";
938
                $ldaptype           = "";
939
                $ldapver            = $authcfg['ldap_protver'];
940
		$ldapname	    = $authcfg['name'];
941
		$ldapscope	    = $authcfg['ldap_scope'];
942 6306b5dd Ermal Lu?i
	} else
943
		return false;
944 55eb9c44 --global
945
	/* first check if there is even an LDAP server populated */ 
946
	if(!$ldapserver) {
947 c61e4626 Ermal Lu?i
		if ($ldapfallback) {
948
			log_error("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager.");
949
			return local_backed($username, $passwd);
950
		} else
951
			log_error("ERROR! ldap_backed() called with no LDAP authentication server defined.");
952
953
		return false;
954 55eb9c44 --global
	}
955
	
956
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
957 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
958 55eb9c44 --global
959
	/* Make sure we can connect to LDAP */
960
	putenv('LDAPTLS_REQCERT=never');
961 c61e4626 Ermal Lu?i
	$error = false;
962
	if (empty($ldapport)) {
963
		if (!($ldap = ldap_connect($ldapserver)))
964
			$error = true;
965
	} else if (!($ldap = ldap_connect($ldapserver, $ldapport)))
966
		$error = true;
967
968
	if ($error == true) {
969 6306b5dd Ermal Lu?i
		log_error("ERROR!  Could not connect to server {$ldapname}.");
970 c61e4626 Ermal Lu?i
		return false;
971 55eb9c44 --global
	}
972 c61e4626 Ermal Lu?i
973 55eb9c44 --global
	/* ok, its up.  now, lets bind as the bind user so we can search it */
974 c61e4626 Ermal Lu?i
	$error = false;
975
	if ($ldapanon == true) {
976
                if (!($res = @ldap_bind($ldap)))
977
                        $error = true;
978
	} else if (!($res = ldap_bind($ldap, $ldapbindun, $ldapbindpw)))
979
		$error = true;
980
981
	if ($error == true) {
982 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
983
		log_error("ERROR! Could not bind to server {$ldapname}.");
984 c61e4626 Ermal Lu?i
		return false;
985 55eb9c44 --global
	}
986
	
987
	/* Get LDAP Authcontainers and split em up. */
988 c61e4626 Ermal Lu?i
	$ldac_splits = split(";", $ldapauthcont);
989 55eb9c44 --global
	
990
	/* setup the usercount so we think we havn't found anyone yet */
991
	$usercount  = 0;
992
993
	/*****************************************************************/
994
	/*  We First find the user based on username and filter          */
995
	/*  Then, once we find the first occurance of that person        */
996
	/*  We set seesion variables to ponit to the OU and DN of the    */
997
	/*  Person.  To later be used by ldap_get_groups.                */
998
	/*  that way we don't have to search twice.                      */
999
	/*****************************************************************/
1000 c61e4626 Ermal Lu?i
	log_error("Now Searching for {$username} in directory.");
1001
	/* Iterate through the user containers for search */
1002
	foreach ($ldac_splits as $i => $ldac_split) {
1003
		/* Make sure we just use the first user we find */
1004
		log_error("Now Searching in server {$ldapname}, container {$ldac_split} with filter {$ldapfilter}.");
1005
		if ($ldapscope == "one")
1006
			$ldapfunc = "ldap_list";
1007
		else
1008
			$ldapfunc = "ldap_search";
1009
		/* Support legacy auth container specification. */
1010 9ae11a62 Scott Ullrich
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn))
1011
			$search	 = @$ldapfunc($ldap,$ldac_split,$ldapfilter);
1012
		else
1013
			$search  = @$ldapfunc($ldap,"{$ldac_split},{$ldapbasedn}",$ldapfilter);
1014 c61e4626 Ermal Lu?i
		if (!$search) {
1015
			log_error("Search resulted in error: " . ldap_error($ldap));
1016
			continue;
1017 55eb9c44 --global
		}
1018 c61e4626 Ermal Lu?i
		$info	 = ldap_get_entries($ldap,$search);
1019
		$matches = $info['count'];
1020 55eb9c44 --global
		if ($matches == 1){
1021 c61e4626 Ermal Lu?i
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1022
			$_SESSION['ldapou'] = $ldac_split[$i];
1023
			$_SESSION['ldapon'] = "true";
1024
			$usercount = 1;
1025
			break;
1026 55eb9c44 --global
		}
1027
	}
1028
1029 c61e4626 Ermal Lu?i
	if ($usercount != 1){
1030 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1031
		log_error("ERROR! Either LDAP search failed, or multiple users were found.");
1032 c61e4626 Ermal Lu?i
		return false;                         
1033 55eb9c44 --global
	}
1034 c61e4626 Ermal Lu?i
1035 55eb9c44 --global
	/* Now lets bind as the user we found */
1036 c61e4626 Ermal Lu?i
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1037 6306b5dd Ermal Lu?i
		log_error("ERROR! Could not login to server {$ldapname} as user {$username}.");
1038
		@ldap_unbind($ldap);
1039 c61e4626 Ermal Lu?i
		return false;
1040 55eb9c44 --global
	}
1041
1042 95feeb92 Chris Buechler
	log_error("Logged in successfully as {$username} via LDAP server {$ldapname} with DN = {$userdn}.");
1043 c61e4626 Ermal Lu?i
1044
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1045 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1046 55eb9c44 --global
1047
	return true;
1048
}
1049
1050 6306b5dd Ermal Lu?i
function radius_backed($username, $passwd, $authcfg){
1051 a13ce628 Ermal Lu?i
	global $debug, $config;
1052 55eb9c44 --global
	$ret = false;
1053
1054 868c6826 Ermal
	require_once("radius.inc");
1055
1056 55eb9c44 --global
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1057 c61e4626 Ermal Lu?i
	if ($authcfg) {
1058
		$radiusservers = array();
1059
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1060
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1061
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1062
	} else
1063 6306b5dd Ermal Lu?i
		return false;
1064 c61e4626 Ermal Lu?i
1065 55eb9c44 --global
	/* Add a new servers to our instance */
1066
	foreach ($radiusservers as $radsrv)
1067
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
1068
1069 6e815096 Ermal
	if (PEAR::isError($rauth->start())) {
1070 55eb9c44 --global
		$retvalue['auth_val'] = 1;
1071
		$retvalue['error'] = $rauth->getError();
1072
		if ($debug)
1073
			printf("Radius start: %s<br>\n", $retvalue['error']);
1074
	}
1075
1076
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1077
1078
	/* Send request */
1079
	$result = $rauth->send();
1080
	if (PEAR::isError($result)) {
1081
		$retvalue['auth_val'] = 1;
1082
		$retvalue['error'] = $result->getMessage();
1083
		if ($debug)
1084
			printf("Radius send failed: %s<br>\n", $retvalue['error']);
1085
	} else if ($result === true) {
1086
		$retvalue['auth_val'] = 2;
1087
		if ($debug)
1088
			printf(gettext("Radius Auth succeeded")."<br>\n");
1089
		$ret = true;
1090
	} else {
1091
		$retvalue['auth_val'] = 3;
1092
		if ($debug)
1093
			printf(gettext("Radius Auth rejected")."<br>\n");
1094
	}
1095
1096
	// close OO RADIUS_AUTHENTICATION
1097
	$rauth->close();
1098
1099
	return $ret;
1100
}
1101
1102 7dd044f2 sullrich
function get_user_expiration_date($username) {
1103 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1104
	if ($user['expires']) 
1105
		return $user['expires'];
1106
}
1107
1108
function is_account_expired($username) {
1109
	$expirydate = get_user_expiration_date($username);
1110
	if ($expirydate) {
1111
		if (strtotime("-1 day") > strtotime(date("m/d/Y",strtotime($expirydate))))
1112
			return true;
1113 7dd044f2 sullrich
	}
1114 a13ce628 Ermal Lu?i
1115
	return false;
1116 7dd044f2 sullrich
}
1117
1118 b4bfd25d sullrich
function is_account_disabled($username) {
1119 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1120
	if (isset($user['disabled']))
1121
		return true;
1122
1123 b4bfd25d sullrich
	return false;
1124
}
1125
1126 c61e4626 Ermal Lu?i
function auth_get_authserver($name) {
1127
        global $config;
1128
1129
        if (is_array($config['system']['authserver'])) {
1130
                foreach ($config['system']['authserver'] as $authcfg) {
1131
                        if ($authcfg['name'] == $name)
1132
                                return $authcfg;
1133
                }
1134
        }
1135 6306b5dd Ermal Lu?i
	if ($name == "Local Database")
1136
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1137
}
1138
1139
function auth_get_authserver_list() {
1140
        global $config;
1141
1142
	$list = array();
1143
1144
        if (is_array($config['system']['authserver'])) {
1145
                foreach ($config['system']['authserver'] as $authcfg) {
1146
			/* Add support for disabled entries? */
1147
			$list[$authcfg['name']] = $authcfg;
1148
                }
1149
        }
1150
1151
	$list["Local Database"] = array( "name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1152
	return $list;
1153 c61e4626 Ermal Lu?i
}
1154
1155 fb0f22c0 Ermal Lu?i
function getUserGroups($username, $authcfg) {
1156
	global $config;
1157
1158
	$allowed_groups = array();
1159
1160
	switch($authcfg['type']) {
1161
        case 'ldap':
1162
		$allowed_groups = @ldap_get_groups($username, $authcfg);
1163
		break;
1164
	case 'radius':
1165
		break;
1166
	default:
1167
		$user = getUserEntry($username);
1168
		$allowed_groups = @local_user_get_groups($user, true);
1169
		break;
1170
	}
1171
1172
	$member_groups = array();
1173
        if (is_array($config['system']['group'])) {
1174
                foreach ($config['system']['group'] as $group)
1175
                        if (in_array($group['name'], $allowed_groups))
1176
				$member_groups[] = $group['name'];
1177
	}
1178
1179
	return $member_groups;
1180
}
1181
1182 c61e4626 Ermal Lu?i
function authenticate_user($username, $password, $authcfg = NULL) {
1183
1184
	if (!$authcfg) {
1185
		return local_backed($username, $password);
1186
	}
1187
1188
	$authenticated = false;
1189
	switch($authcfg['type']) {
1190
        case 'ldap':
1191
                if (ldap_backed($username, $password, $authcfg))
1192
                        $authenticated = true;
1193
                break;
1194
        case 'radius':
1195
                if (radius_backed($username, $password, $authcfg))
1196
                        $authenticated = true;
1197
                break;
1198
        default:
1199
                /* lookup user object by name */
1200
                if (local_backed($username, $password))
1201
                        $authenticated = true;
1202
                break;
1203
        }
1204
1205
	return $authenticated;
1206
}
1207
1208 6306b5dd Ermal Lu?i
function session_auth() {
1209
	global $HTTP_SERVER_VARS, $config, $_SESSION, $page;
1210 55eb9c44 --global
1211
	session_start();
1212
1213
	/* Validate incoming login request */
1214
	if (isset($_POST['login'])) {
1215 6306b5dd Ermal Lu?i
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1216
		if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) || 
1217
		    authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1218
			$_SESSION['Logged_In'] = "True";
1219
			$_SESSION['Username'] = $_POST['usernamefld'];
1220
			$_SESSION['last_access'] = time();
1221 4fc3855f smos
			if(! isset($config['system']['webgui']['quietlogin'])) {
1222
				log_auth("Successful webConfigurator login for user '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1223
			}
1224 f23e6363 Ermal
			$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1225 92140621 Ermal
			if (isset($_POST['postafterlogin']))
1226
				return true;
1227 80b292f3 Ermal
			else {
1228
				if (empty($page))
1229
					$page = "/";
1230
				header("Location: {$page}");
1231
			}
1232 f23e6363 Ermal
			exit;
1233 a13ce628 Ermal Lu?i
		} else {
1234
			/* give the user an error message */
1235
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1236 65f7fba8 Scott Ullrich
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1237 a13ce628 Ermal Lu?i
			if(isAjax()) {
1238
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1239
				return;
1240 55eb9c44 --global
			}
1241
		}
1242
	}
1243
1244
	/* Show login page if they aren't logged in */
1245 409105ec Ermal Lu?i
	if (empty($_SESSION['Logged_In']))
1246 55eb9c44 --global
		return false;
1247
1248
	/* If session timeout isn't set, we don't mark sessions stale */
1249 02647583 Ermal
	if (!isset($config['system']['webgui']['session_timeout'])) {
1250 bdadaf3c Chris Buechler
		/* Default to 4 hour timeout if one is not set */
1251
		if ($_SESSION['last_access'] < (time() - 14400)) {
1252
			$_GET['logout'] = true;
1253
			$_SESSION['Logout'] = true;
1254 9a985f9e Ermal
		} else
1255
			$_SESSION['last_access'] = time();	
1256 02647583 Ermal
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1257
		/* only update if it wasn't ajax */
1258
		if (!isAjax())
1259
			$_SESSION['last_access'] = time();
1260 bdadaf3c Chris Buechler
	} else {
1261 55eb9c44 --global
		/* Check for stale session */
1262
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1263
			$_GET['logout'] = true;
1264
			$_SESSION['Logout'] = true;
1265
		} else {
1266
			/* only update if it wasn't ajax */
1267
			if (!isAjax())
1268
				$_SESSION['last_access'] = time();
1269
		}
1270
	}
1271
1272
	/* user hit the logout button */
1273
	if (isset($_GET['logout'])) {
1274
1275
		if ($_SESSION['Logout'])
1276
			log_error("Session timed out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1277
		else
1278
			log_error("User logged out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
1279
1280
		/* wipe out $_SESSION */
1281
		$_SESSION = array();
1282
1283
		if (isset($_COOKIE[session_name()]))
1284
			setcookie(session_name(), '', time()-42000, '/');
1285
1286
		/* and destroy it */
1287
		session_destroy();
1288
1289
		$scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
1290
		$scriptElms = count($scriptName);
1291
		$scriptName = $scriptName[$scriptElms-1];
1292
1293
		if (isAjax())
1294
			return false;
1295
1296
		/* redirect to page the user is on, it'll prompt them to login again */
1297 6dc88d53 Ermal Luci
		Header("Location: {$scriptName}");
1298 55eb9c44 --global
1299
		return false;
1300
	}
1301
1302
	/*
1303
	 * this is for debugging purpose if you do not want to use Ajax
1304
	 * to submit a HTML form. It basically diables the observation
1305
	 * of the submit event and hence does not trigger Ajax.
1306
	 */
1307 f23e6363 Ermal
	if ($_GET['disable_ajax'])
1308 55eb9c44 --global
		$_SESSION['NO_AJAX'] = "True";
1309
1310
	/*
1311
	 * Same to re-enable Ajax.
1312
	 */
1313 f23e6363 Ermal
	if ($_GET['enable_ajax'])
1314 55eb9c44 --global
		unset($_SESSION['NO_AJAX']);
1315
1316
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
1317
	return true;
1318
}
1319
1320 ee4fc984 Ermal
?>