Project

General

Profile

Download (46.1 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	auth.inc
4
*/
5
/* ====================================================================
6
 *	Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
7
 *	Copyright (c)  2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 *	Copyright (c)  2006 Paul Taylor <paultaylor@winn-dixie.com>
9
 *	Copyright (c)  2003-2006 Manuel Kasper <mk@neon1.net>
10
 *
11
 *	Redistribution and use in source and binary forms, with or without modification,
12
 *	are permitted provided that the following conditions are met:
13
 *
14
 *	1. Redistributions of source code must retain the above copyright notice,
15
 *		this list of conditions and the following disclaimer.
16
 *
17
 *	2. Redistributions in binary form must reproduce the above copyright
18
 *		notice, this list of conditions and the following disclaimer in
19
 *		the documentation and/or other materials provided with the
20
 *		distribution.
21
 *
22
 *	3. All advertising materials mentioning features or use of this software
23
 *		must display the following acknowledgment:
24
 *		"This product includes software developed by the pfSense Project
25
 *		 for use in the pfSense software distribution. (http://www.pfsense.org/).
26
 *
27
 *	4. The names "pfSense" and "pfSense Project" must not be used to
28
 *		 endorse or promote products derived from this software without
29
 *		 prior written permission. For written permission, please contact
30
 *		 coreteam@pfsense.org.
31
 *
32
 *	5. Products derived from this software may not be called "pfSense"
33
 *		nor may "pfSense" appear in their names without prior written
34
 *		permission of the Electric Sheep Fencing, LLC.
35
 *
36
 *	6. Redistributions of any form whatsoever must retain the following
37
 *		acknowledgment:
38
 *
39
 *	"This product includes software developed by the pfSense Project
40
 *	for use in the pfSense software distribution (http://www.pfsense.org/).
41
 *
42
 *	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
43
 *	EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44
 *	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
45
 *	PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
46
 *	ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47
 *	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
48
 *	NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
49
 *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50
 *	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51
 *	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52
 *	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53
 *	OF THE POSSIBILITY OF SUCH DAMAGE.
54
 *
55
 *	====================================================================
56
 *
57
 */
58
/*
59
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
60
 * file courtesy of Michael Retterklieber.
61
 */
62
if (!$do_not_include_config_gui_inc) {
63
	require_once("config.gui.inc");
64
}
65

    
66
// Will be changed to false if security checks fail
67
$security_passed = true;
68

    
69
/* If this function doesn't exist, we're being called from Captive Portal or
70
   another internal subsystem which does not include authgui.inc */
71
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
72
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
73
	$found_host = false;
74

    
75
	/* Either a IPv6 address with or without a alternate port */
76
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
77
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
78
		/* v6 address has more parts, drop the last part */
79
		if (count($http_host_port) > 1) {
80
			array_pop($http_host_port);
81
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
82
		} else {
83
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
84
		}
85
	} else {
86
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
87
		$http_host = $http_host[0];
88
	}
89
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
90
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
91
		$found_host = true;
92
	}
93
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
94
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
95
		$found_host = true;
96
	}
97

    
98
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
99
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
100
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
101
				$found_host = true;
102
				break;
103
			}
104
		}
105
	}
106

    
107
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
108
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
109
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
110
				$found_host = true;
111
				break;
112
			}
113
		}
114
	}
115

    
116
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
117
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
118
		foreach ($althosts as $ah) {
119
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
120
				$found_host = true;
121
				break;
122
			}
123
		}
124
	}
125

    
126
	if ($found_host == false) {
127
		if (!security_checks_disabled()) {
128
			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."));
129
			exit;
130
		}
131
		$security_passed = false;
132
	}
133
}
134

    
135
// If the HTTP_REFERER is something other than ourselves then disallow.
136
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
137
	if ($_SERVER['HTTP_REFERER']) {
138
		if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
139
			if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
140
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
141
				header("Refresh: 1; url=index.php");
142
?>
143
<!DOCTYPE html>
144
<html lang="en">
145
<head>
146
	<link rel="stylesheet" href="/bootstrap/css/pfSense.css" />
147
	<title><?=gettext("Redirecting..."); ?></title>
148
</head>
149
<body id="error" class="no-menu">
150
	<div id="jumbotron">
151
		<div class="container">
152
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
153
				<p><?=gettext("Redirecting to the dashboard...")?></p>
154
			</div>
155
		</div>
156
	</div>
157
</body>
158
</html>
159
<?php
160
				exit;
161
			}
162
		}
163
		$found_host = false;
164
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
165
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
166
		if ($referrer_host) {
167
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
168
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
169
				$found_host = true;
170
			}
171

    
172
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
173
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
174
				foreach ($althosts as $ah) {
175
					if (strcasecmp($referrer_host, $ah) == 0) {
176
						$found_host = true;
177
						break;
178
					}
179
				}
180
			}
181

    
182
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
183
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
184
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
185
						$found_host = true;
186
						break;
187
					}
188
				}
189
			}
190

    
191
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
192
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
193
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
194
						$found_host = true;
195
						break;
196
					}
197
				}
198
			}
199

    
200
			if (!$found_host) {
201
				$interface_list_ips = get_configured_ip_addresses();
202
				foreach ($interface_list_ips as $ilips) {
203
					if (strcasecmp($referrer_host, $ilips) == 0) {
204
						$found_host = true;
205
						break;
206
					}
207
				}
208
				$interface_list_ipv6s = get_configured_ipv6_addresses();
209
				foreach ($interface_list_ipv6s as $ilipv6s) {
210
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
211
						$found_host = true;
212
						break;
213
					}
214
				}
215
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
216
					// allow SSH port forwarded connections and links from localhost
217
					$found_host = true;
218
				}
219
			}
220
		}
221
		if ($found_host == false) {
222
			if (!security_checks_disabled()) {
223
				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.");
224
				exit;
225
			}
226
			$security_passed = false;
227
		}
228
	} else {
229
		$security_passed = false;
230
	}
231
}
232

    
233
if (function_exists("display_error_form") && $security_passed) {
234
	/* Security checks passed, so it should be OK to turn them back on */
235
	restore_security_checks();
236
}
237
unset($security_passed);
238

    
239
$groupindex = index_groups();
240
$userindex = index_users();
241

    
242
function index_groups() {
243
	global $g, $debug, $config, $groupindex;
244

    
245
	$groupindex = array();
246

    
247
	if (is_array($config['system']['group'])) {
248
		$i = 0;
249
		foreach ($config['system']['group'] as $groupent) {
250
			$groupindex[$groupent['name']] = $i;
251
			$i++;
252
		}
253
	}
254

    
255
	return ($groupindex);
256
}
257

    
258
function index_users() {
259
	global $g, $debug, $config;
260

    
261
	if (is_array($config['system']['user'])) {
262
		$i = 0;
263
		foreach ($config['system']['user'] as $userent) {
264
			$userindex[$userent['name']] = $i;
265
			$i++;
266
		}
267
	}
268

    
269
	return ($userindex);
270
}
271

    
272
function & getUserEntry($name) {
273
	global $debug, $config, $userindex;
274
	if (isset($userindex[$name])) {
275
		return $config['system']['user'][$userindex[$name]];
276
	}
277
}
278

    
279
function & getUserEntryByUID($uid) {
280
	global $debug, $config;
281

    
282
	if (is_array($config['system']['user'])) {
283
		foreach ($config['system']['user'] as & $user) {
284
			if ($user['uid'] == $uid) {
285
				return $user;
286
			}
287
		}
288
	}
289

    
290
	return false;
291
}
292

    
293
function & getGroupEntry($name) {
294
	global $debug, $config, $groupindex;
295
	if (isset($groupindex[$name])) {
296
		return $config['system']['group'][$groupindex[$name]];
297
	}
298
}
299

    
300
function & getGroupEntryByGID($gid) {
301
	global $debug, $config;
302

    
303
	if (is_array($config['system']['group'])) {
304
		foreach ($config['system']['group'] as & $group) {
305
			if ($group['gid'] == $gid) {
306
				return $group;
307
			}
308
		}
309
	}
310

    
311
	return false;
312
}
313

    
314
function get_user_privileges(& $user) {
315

    
316
	$privs = $user['priv'];
317
	if (!is_array($privs)) {
318
		$privs = array();
319
	}
320

    
321
	$names = local_user_get_groups($user, true);
322

    
323
	foreach ($names as $name) {
324
		$group = getGroupEntry($name);
325
		if (is_array($group['priv'])) {
326
			$privs = array_merge($privs, $group['priv']);
327
		}
328
	}
329

    
330
	return $privs;
331
}
332

    
333
function userHasPrivilege($userent, $privid = false) {
334

    
335
	if (!$privid || !is_array($userent)) {
336
		return false;
337
	}
338

    
339
	$privs = get_user_privileges($userent);
340

    
341
	if (!is_array($privs)) {
342
		return false;
343
	}
344

    
345
	if (!in_array($privid, $privs)) {
346
		return false;
347
	}
348

    
349
	return true;
350
}
351

    
352
function local_backed($username, $passwd) {
353

    
354
	$user = getUserEntry($username);
355
	if (!$user) {
356
		return false;
357
	}
358

    
359
	if (is_account_disabled($username) || is_account_expired($username)) {
360
		return false;
361
	}
362

    
363
	if ($user['password']) {
364
		if (crypt($passwd, $user['password']) == $user['password']) {
365
			return true;
366
		}
367
	}
368

    
369
	if ($user['md5-hash']) {
370
		if (md5($passwd) == $user['md5-hash']) {
371
			return true;
372
		}
373
	}
374

    
375
	return false;
376
}
377

    
378
function local_sync_accounts() {
379
	global $debug, $config;
380
	conf_mount_rw();
381

    
382
	/* remove local users to avoid uid conflicts */
383
	$fd = popen("/usr/sbin/pw usershow -a", "r");
384
	if ($fd) {
385
		while (!feof($fd)) {
386
			$line = explode(":", fgets($fd));
387
			if (((!strncmp($line[0], "_", 1)) || ($line[2] < 2000) || ($line[2] > 65000)) && ($line[0] != "admin")) {
388
				continue;
389
			}
390
			/*
391
			 * If a crontab was created to user, pw userdel will be interactive and
392
			 * can cause issues. Just remove crontab before run it when necessary
393
			 */
394
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
395
			$cmd = "/usr/sbin/pw userdel -n '{$line[0]}'";
396
			if ($debug) {
397
				log_error(sprintf(gettext("Running: %s"), $cmd));
398
			}
399
			mwexec($cmd);
400
		}
401
		pclose($fd);
402
	}
403

    
404
	/* remove local groups to avoid gid conflicts */
405
	$gids = array();
406
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
407
	if ($fd) {
408
		while (!feof($fd)) {
409
			$line = explode(":", fgets($fd));
410
			if (!strncmp($line[0], "_", 1)) {
411
				continue;
412
			}
413
			if ($line[2] < 2000) {
414
				continue;
415
			}
416
			if ($line[2] > 65000) {
417
				continue;
418
			}
419
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
420
			if ($debug) {
421
				log_error(sprintf(gettext("Running: %s"), $cmd));
422
			}
423
			mwexec($cmd);
424
		}
425
		pclose($fd);
426
	}
427

    
428
	/* make sure the all group exists */
429
	$allgrp = getGroupEntryByGID(1998);
430
	local_group_set($allgrp, true);
431

    
432
	/* sync all local users */
433
	if (is_array($config['system']['user'])) {
434
		foreach ($config['system']['user'] as $user) {
435
			local_user_set($user);
436
		}
437
	}
438

    
439
	/* sync all local groups */
440
	if (is_array($config['system']['group'])) {
441
		foreach ($config['system']['group'] as $group) {
442
			local_group_set($group);
443
		}
444
	}
445

    
446
	conf_mount_ro();
447

    
448
}
449

    
450
function local_user_set(& $user) {
451
	global $g, $debug;
452

    
453
	if (empty($user['password'])) {
454
		log_error("There is something wrong in your config because user {$user['name']} password is missing!");
455
		return;
456
	}
457

    
458
	conf_mount_rw();
459

    
460
	$home_base = "/home/";
461
	$user_uid = $user['uid'];
462
	$user_name = $user['name'];
463
	$user_home = "{$home_base}{$user_name}";
464
	$user_shell = "/etc/rc.initial";
465
	$user_group = "nobody";
466

    
467
	// Ensure $home_base exists and is writable
468
	if (!is_dir($home_base)) {
469
		mkdir($home_base, 0755);
470
	}
471

    
472
	$lock_account = false;
473
	/* configure shell type */
474
	/* Cases here should be ordered by most privileged to least privileged. */
475
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
476
		$user_shell = "/bin/tcsh";
477
	} elseif (userHasPrivilege($user, "user-copy-files")) {
478
		$user_shell = "/usr/local/bin/scponly";
479
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
480
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
481
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
482
		$user_shell = "/sbin/nologin";
483
	} else {
484
		$user_shell = "/sbin/nologin";
485
		$lock_account = true;
486
	}
487

    
488
	/* Lock out disabled or expired users, unless it's root/admin. */
489
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
490
		$user_shell = "/sbin/nologin";
491
		$lock_account = true;
492
	}
493

    
494
	/* root user special handling */
495
	if ($user_uid == 0) {
496
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
497
		if ($debug) {
498
			log_error(sprintf(gettext("Running: %s"), $cmd));
499
		}
500
		$fd = popen($cmd, "w");
501
		fwrite($fd, $user['password']);
502
		pclose($fd);
503
		$user_group = "wheel";
504
		$user_home = "/root";
505
		$user_shell = "/etc/rc.initial";
506
	}
507

    
508
	/* read from pw db */
509
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
510
	$pwread = fgets($fd);
511
	pclose($fd);
512
	$userattrs = explode(":", trim($pwread));
513

    
514
	/* determine add or mod */
515
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
516
		$user_op = "useradd -m -k /etc/skel -o";
517
	} else {
518
		$user_op = "usermod";
519
	}
520

    
521
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
522
	/* add or mod pw db */
523
	$cmd = "/usr/sbin/pw {$user_op} -q -u {$user_uid} -n {$user_name}".
524
			" -g {$user_group} -s {$user_shell} -d {$user_home}".
525
			" -c ".escapeshellarg($comment)." -H 0 2>&1";
526

    
527
	if ($debug) {
528
		log_error(sprintf(gettext("Running: %s"), $cmd));
529
	}
530
	$fd = popen($cmd, "w");
531
	fwrite($fd, $user['password']);
532
	pclose($fd);
533

    
534
	/* create user directory if required */
535
	if (!is_dir($user_home)) {
536
		mkdir($user_home, 0700);
537
	}
538
	@chown($user_home, $user_name);
539
	@chgrp($user_home, $user_group);
540

    
541
	/* write out ssh authorized key file */
542
	if ($user['authorizedkeys']) {
543
		if (!is_dir("{$user_home}/.ssh")) {
544
			@mkdir("{$user_home}/.ssh", 0700);
545
			@chown("{$user_home}/.ssh", $user_name);
546
		}
547
		$keys = base64_decode($user['authorizedkeys']);
548
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
549
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
550
	} else {
551
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
552
	}
553

    
554
	$un = $lock_account ? "" : "un";
555
	exec("/usr/sbin/pw {$un}lock {$user_name} -q 2>/dev/null");
556

    
557
	conf_mount_ro();
558
}
559

    
560
function local_user_del($user) {
561
	global $debug;
562

    
563
	/* remove all memberships */
564
	local_user_set_groups($user);
565

    
566
	/* Don't remove /root */
567
	if ($user['uid'] != 0) {
568
		$rmhome = "-r";
569
	}
570

    
571
	/* read from pw db */
572
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
573
	$pwread = fgets($fd);
574
	pclose($fd);
575
	$userattrs = explode(":", trim($pwread));
576

    
577
	if ($userattrs[0] != $user['name']) {
578
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
579
		return;
580
	}
581

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

    
585
	if ($debug) {
586
		log_error(sprintf(gettext("Running: %s"), $cmd));
587
	}
588
	mwexec($cmd);
589

    
590
	/* Delete user from groups needs a call to write_config() */
591
	local_group_del_user($user);
592
}
593

    
594
function local_user_set_password(&$user, $password) {
595

    
596
	$user['password'] = crypt($password);
597
	$user['md5-hash'] = md5($password);
598

    
599
	// Converts ascii to unicode.
600
	$astr = (string) $password;
601
	$ustr = '';
602
	for ($i = 0; $i < strlen($astr); $i++) {
603
		$a = ord($astr{$i}) << 8;
604
		$ustr .= sprintf("%X", $a);
605
	}
606

    
607
}
608

    
609
function local_user_get_groups($user, $all = false) {
610
	global $debug, $config;
611

    
612
	$groups = array();
613
	if (!is_array($config['system']['group'])) {
614
		return $groups;
615
	}
616

    
617
	foreach ($config['system']['group'] as $group) {
618
		if ($all || (!$all && ($group['name'] != "all"))) {
619
			if (is_array($group['member'])) {
620
				if (in_array($user['uid'], $group['member'])) {
621
					$groups[] = $group['name'];
622
				}
623
			}
624
		}
625
	}
626

    
627
	if ($all) {
628
		$groups[] = "all";
629
	}
630

    
631
	sort($groups);
632

    
633
	return $groups;
634

    
635
}
636

    
637
function local_user_set_groups($user, $new_groups = NULL) {
638
	global $debug, $config, $groupindex;
639

    
640
	if (!is_array($config['system']['group'])) {
641
		return;
642
	}
643

    
644
	$cur_groups = local_user_get_groups($user, true);
645
	$mod_groups = array();
646

    
647
	if (!is_array($new_groups)) {
648
		$new_groups = array();
649
	}
650

    
651
	if (!is_array($cur_groups)) {
652
		$cur_groups = array();
653
	}
654

    
655
	/* determine which memberships to add */
656
	foreach ($new_groups as $groupname) {
657
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
658
			continue;
659
		}
660
		$group = & $config['system']['group'][$groupindex[$groupname]];
661
		$group['member'][] = $user['uid'];
662
		$mod_groups[] = $group;
663
	}
664
	unset($group);
665

    
666
	/* determine which memberships to remove */
667
	foreach ($cur_groups as $groupname) {
668
		if (in_array($groupname, $new_groups)) {
669
			continue;
670
		}
671
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
672
			continue;
673
		}
674
		$group = & $config['system']['group'][$groupindex[$groupname]];
675
		if (is_array($group['member'])) {
676
			$index = array_search($user['uid'], $group['member']);
677
			array_splice($group['member'], $index, 1);
678
			$mod_groups[] = $group;
679
		}
680
	}
681
	unset($group);
682

    
683
	/* sync all modified groups */
684
	foreach ($mod_groups as $group) {
685
		local_group_set($group);
686
	}
687
}
688

    
689
function local_group_del_user($user) {
690
	global $config;
691

    
692
	if (!is_array($config['system']['group'])) {
693
		return;
694
	}
695

    
696
	foreach ($config['system']['group'] as $group) {
697
		if (is_array($group['member'])) {
698
			foreach ($group['member'] as $idx => $uid) {
699
				if ($user['uid'] == $uid) {
700
					unset($config['system']['group']['member'][$idx]);
701
				}
702
			}
703
		}
704
	}
705
}
706

    
707
function local_group_set($group, $reset = false) {
708
	global $debug;
709

    
710
	$group_name = $group['name'];
711
	$group_gid = $group['gid'];
712
	$group_members = '';
713
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
714
		$group_members = implode(",", $group['member']);
715
	}
716

    
717
	if (empty($group_name)) {
718
		return;
719
	}
720

    
721
	/* read from group db */
722
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
723
	$pwread = fgets($fd);
724
	pclose($fd);
725

    
726
	/* determine add or mod */
727
	if (!strncmp($pwread, "pw:", 3)) {
728
		$group_op = "groupadd";
729
	} else {
730
		$group_op = "groupmod";
731
	}
732

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

    
736
	if ($debug) {
737
		log_error(sprintf(gettext("Running: %s"), $cmd));
738
	}
739
	mwexec($cmd);
740

    
741
}
742

    
743
function local_group_del($group) {
744
	global $debug;
745

    
746
	/* delete from group db */
747
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
748

    
749
	if ($debug) {
750
		log_error(sprintf(gettext("Running: %s"), $cmd));
751
	}
752
	mwexec($cmd);
753
}
754

    
755
function ldap_test_connection($authcfg) {
756
	global $debug, $config, $g;
757

    
758
	if ($authcfg) {
759
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
760
			$ldapproto = "ldap";
761
		} else {
762
			$ldapproto = "ldaps";
763
		}
764
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
765
		$ldapport = $authcfg['ldap_port'];
766
		if (!empty($ldapport)) {
767
			$ldapserver .= ":{$ldapport}";
768
		}
769
		$ldapbasedn = $authcfg['ldap_basedn'];
770
		$ldapbindun = $authcfg['ldap_binddn'];
771
		$ldapbindpw = $authcfg['ldap_bindpw'];
772
	} else {
773
		return false;
774
	}
775

    
776
	/* first check if there is even an LDAP server populated */
777
	if (!$ldapserver) {
778
		return false;
779
	}
780

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

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

    
790
	if ($error == true) {
791
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
792
		return false;
793
	}
794

    
795
	return true;
796
}
797

    
798
function ldap_setup_caenv($authcfg) {
799
	global $g;
800
	require_once("certs.inc");
801

    
802
	unset($caref);
803
	if (empty($authcfg['ldap_caref']) || !strstr($authcfg['ldap_urltype'], "SSL")) {
804
		putenv('LDAPTLS_REQCERT=never');
805
		return;
806
	} else {
807
		$caref = lookup_ca($authcfg['ldap_caref']);
808
		if (!$caref) {
809
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
810
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
811
			putenv('LDAPTLS_REQCERT=hard');
812
			return;
813
		}
814
		if (!is_dir("{$g['varrun_path']}/certs")) {
815
			@mkdir("{$g['varrun_path']}/certs");
816
		}
817
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
818
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
819
		}
820
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", base64_decode($caref['crt']));
821
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
822
		putenv('LDAPTLS_REQCERT=hard');
823
		/* XXX: Probably even the hashed link should be created for this? */
824
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
825
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
826
	}
827
}
828

    
829
function ldap_test_bind($authcfg) {
830
	global $debug, $config, $g;
831

    
832
	if ($authcfg) {
833
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
834
			$ldapproto = "ldap";
835
		} else {
836
			$ldapproto = "ldaps";
837
		}
838
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
839
		$ldapport = $authcfg['ldap_port'];
840
		if (!empty($ldapport)) {
841
			$ldapserver .= ":{$ldapport}";
842
		}
843
		$ldapbasedn = $authcfg['ldap_basedn'];
844
		$ldapbindun = $authcfg['ldap_binddn'];
845
		$ldapbindpw = $authcfg['ldap_bindpw'];
846
		$ldapver = $authcfg['ldap_protver'];
847
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
848
		if (empty($ldapbndun) || empty($ldapbindpw)) {
849
			$ldapanon = true;
850
		} else {
851
			$ldapanon = false;
852
		}
853
	} else {
854
		return false;
855
	}
856

    
857
	/* first check if there is even an LDAP server populated */
858
	if (!$ldapserver) {
859
		return false;
860
	}
861

    
862
	/* Setup CA environment if needed. */
863
	ldap_setup_caenv($authcfg);
864

    
865
	/* connect and see if server is up */
866
	$error = false;
867
	if (!($ldap = ldap_connect($ldapserver))) {
868
		$error = true;
869
	}
870

    
871
	if ($error == true) {
872
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
873
		return false;
874
	}
875

    
876
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
877
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
878
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
879
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
880
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
881

    
882
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
883
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
884
	if ($ldapanon == true) {
885
		if (!($res = @ldap_bind($ldap))) {
886
			@ldap_close($ldap);
887
			return false;
888
		}
889
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
890
		@ldap_close($ldap);
891
		return false;
892
	}
893

    
894
	@ldap_unbind($ldap);
895

    
896
	return true;
897
}
898

    
899
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
900
	global $debug, $config, $g;
901

    
902
	if (!function_exists("ldap_connect")) {
903
		return;
904
	}
905

    
906
	$ous = array();
907

    
908
	if ($authcfg) {
909
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
910
			$ldapproto = "ldap";
911
		} else {
912
			$ldapproto = "ldaps";
913
		}
914
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
915
		$ldapport = $authcfg['ldap_port'];
916
		if (!empty($ldapport)) {
917
			$ldapserver .= ":{$ldapport}";
918
		}
919
		$ldapbasedn = $authcfg['ldap_basedn'];
920
		$ldapbindun = $authcfg['ldap_binddn'];
921
		$ldapbindpw = $authcfg['ldap_bindpw'];
922
		$ldapver = $authcfg['ldap_protver'];
923
		if (empty($ldapbindun) || empty($ldapbindpw)) {
924
			$ldapanon = true;
925
		} else {
926
			$ldapanon = false;
927
		}
928
		$ldapname = $authcfg['name'];
929
		$ldapfallback = false;
930
		$ldapscope = $authcfg['ldap_scope'];
931
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
932
	} else {
933
		return false;
934
	}
935

    
936
	/* first check if there is even an LDAP server populated */
937
	if (!$ldapserver) {
938
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
939
		return $ous;
940
	}
941

    
942
	/* Setup CA environment if needed. */
943
	ldap_setup_caenv($authcfg);
944

    
945
	/* connect and see if server is up */
946
	$error = false;
947
	if (!($ldap = ldap_connect($ldapserver))) {
948
		$error = true;
949
	}
950

    
951
	if ($error == true) {
952
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
953
		return $ous;
954
	}
955

    
956
	$ldapfilter = "(|(ou=*)(cn=Users))";
957

    
958
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
959
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
960
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
961
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
962
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
963

    
964
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
965
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
966
	if ($ldapanon == true) {
967
		if (!($res = @ldap_bind($ldap))) {
968
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
969
			@ldap_close($ldap);
970
			return $ous;
971
		}
972
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
973
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
974
		@ldap_close($ldap);
975
		return $ous;
976
	}
977

    
978
	if ($ldapscope == "one") {
979
		$ldapfunc = "ldap_list";
980
	} else {
981
		$ldapfunc = "ldap_search";
982
	}
983

    
984
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
985
	$info = @ldap_get_entries($ldap, $search);
986

    
987
	if (is_array($info)) {
988
		foreach ($info as $inf) {
989
			if (!$show_complete_ou) {
990
				$inf_split = explode(",", $inf['dn']);
991
				$ou = $inf_split[0];
992
				$ou = str_replace("OU=", "", $ou);
993
				$ou = str_replace("CN=", "", $ou);
994
			} else {
995
				if ($inf['dn']) {
996
					$ou = $inf['dn'];
997
				}
998
			}
999
			if ($ou) {
1000
				$ous[] = $ou;
1001
			}
1002
		}
1003
	}
1004

    
1005
	@ldap_unbind($ldap);
1006

    
1007
	return $ous;
1008
}
1009

    
1010
function ldap_get_groups($username, $authcfg) {
1011
	global $debug, $config;
1012

    
1013
	if (!function_exists("ldap_connect")) {
1014
		return;
1015
	}
1016

    
1017
	if (!$username) {
1018
		return false;
1019
	}
1020

    
1021
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1022
		$username_split = explode("@", $username);
1023
		$username = $username_split[0];
1024
	}
1025

    
1026
	if (stristr($username, "\\")) {
1027
		$username_split = explode("\\", $username);
1028
		$username = $username_split[0];
1029
	}
1030

    
1031
	//log_error("Getting LDAP groups for {$username}.");
1032
	if ($authcfg) {
1033
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
1034
			$ldapproto = "ldap";
1035
		} else {
1036
			$ldapproto = "ldaps";
1037
		}
1038
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1039
		$ldapport = $authcfg['ldap_port'];
1040
		if (!empty($ldapport)) {
1041
			$ldapserver .= ":{$ldapport}";
1042
		}
1043
		$ldapbasedn = $authcfg['ldap_basedn'];
1044
		$ldapbindun = $authcfg['ldap_binddn'];
1045
		$ldapbindpw = $authcfg['ldap_bindpw'];
1046
		$ldapauthcont = $authcfg['ldap_authcn'];
1047
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1048
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1049
		if (isset($authcfg['ldap_rfc2307'])) {
1050
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1051
		} else {
1052
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1053
		}
1054
		$ldaptype = "";
1055
		$ldapver = $authcfg['ldap_protver'];
1056
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1057
			$ldapanon = true;
1058
		} else {
1059
			$ldapanon = false;
1060
		}
1061
		$ldapname = $authcfg['name'];
1062
		$ldapfallback = false;
1063
		$ldapscope = $authcfg['ldap_scope'];
1064
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
1065
	} else {
1066
		return false;
1067
	}
1068

    
1069
	if (isset($authcfg['ldap_rfc2307'])) {
1070
		$ldapdn = $ldapbasedn;
1071
	} else {
1072
		$ldapdn = $_SESSION['ldapdn'];
1073
	}
1074

    
1075
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1076
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1077
	$memberof = array();
1078

    
1079
	/* Setup CA environment if needed. */
1080
	ldap_setup_caenv($authcfg);
1081

    
1082
	/* connect and see if server is up */
1083
	$error = false;
1084
	if (!($ldap = ldap_connect($ldapserver))) {
1085
		$error = true;
1086
	}
1087

    
1088
	if ($error == true) {
1089
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1090
		return memberof;
1091
	}
1092

    
1093
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1094
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1095
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1096
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1097
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1098

    
1099
	/* bind as user that has rights to read group attributes */
1100
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1101
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1102
	if ($ldapanon == true) {
1103
		if (!($res = @ldap_bind($ldap))) {
1104
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1105
			@ldap_close($ldap);
1106
			return false;
1107
		}
1108
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1109
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1110
		@ldap_close($ldap);
1111
		return memberof;
1112
	}
1113

    
1114
	/* get groups from DN found */
1115
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1116
	/* since we know the DN is in $_SESSION['ldapdn'] */
1117
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1118
	if ($ldapscope == "one") {
1119
		$ldapfunc = "ldap_list";
1120
	} else {
1121
		$ldapfunc = "ldap_search";
1122
	}
1123

    
1124
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1125
	$info = @ldap_get_entries($ldap, $search);
1126

    
1127
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1128

    
1129
	if (is_array($gresults)) {
1130
		/* Iterate through the groups and throw them into an array */
1131
		foreach ($gresults as $grp) {
1132
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1133
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1134
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1135
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1136
			}
1137
		}
1138
	}
1139

    
1140
	/* Time to close LDAP connection */
1141
	@ldap_unbind($ldap);
1142

    
1143
	$groups = print_r($memberof, true);
1144

    
1145
	//log_error("Returning groups ".$groups." for user $username");
1146

    
1147
	return $memberof;
1148
}
1149

    
1150
function ldap_format_host($host) {
1151
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1152
}
1153

    
1154
function ldap_backed($username, $passwd, $authcfg) {
1155
	global $debug, $config;
1156

    
1157
	if (!$username) {
1158
		return;
1159
	}
1160

    
1161
	if (!function_exists("ldap_connect")) {
1162
		return;
1163
	}
1164

    
1165
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1166
		$username_split = explode("@", $username);
1167
		$username = $username_split[0];
1168
	}
1169
	if (stristr($username, "\\")) {
1170
		$username_split = explode("\\", $username);
1171
		$username = $username_split[0];
1172
	}
1173

    
1174
	if ($authcfg) {
1175
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
1176
			$ldapproto = "ldap";
1177
		} else {
1178
			$ldapproto = "ldaps";
1179
		}
1180
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1181
		$ldapport = $authcfg['ldap_port'];
1182
		if (!empty($ldapport)) {
1183
			$ldapserver .= ":{$ldapport}";
1184
		}
1185
		$ldapbasedn = $authcfg['ldap_basedn'];
1186
		$ldapbindun = $authcfg['ldap_binddn'];
1187
		$ldapbindpw = $authcfg['ldap_bindpw'];
1188
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1189
			$ldapanon = true;
1190
		} else {
1191
			$ldapanon = false;
1192
		}
1193
		$ldapauthcont = $authcfg['ldap_authcn'];
1194
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1195
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1196
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1197
		$ldapfilter = "";
1198
		if (!$ldapextendedqueryenabled) {
1199
			$ldapfilter = "({$ldapnameattribute}={$username})";
1200
		} else {
1201
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1202
		}
1203
		$ldaptype = "";
1204
		$ldapver = $authcfg['ldap_protver'];
1205
		$ldapname = $authcfg['name'];
1206
		$ldapscope = $authcfg['ldap_scope'];
1207
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
1208
	} else {
1209
		return false;
1210
	}
1211

    
1212
	/* first check if there is even an LDAP server populated */
1213
	if (!$ldapserver) {
1214
		if ($ldapfallback) {
1215
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1216
			return local_backed($username, $passwd);
1217
		} else {
1218
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1219
		}
1220

    
1221
		return false;
1222
	}
1223

    
1224
	/* Setup CA environment if needed. */
1225
	ldap_setup_caenv($authcfg);
1226

    
1227
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1228
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1229
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1230
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1231
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1232

    
1233
	/* Make sure we can connect to LDAP */
1234
	$error = false;
1235
	if (!($ldap = ldap_connect($ldapserver))) {
1236
		$error = true;
1237
	}
1238

    
1239
	if ($error == true) {
1240
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1241
		return false;
1242
	}
1243

    
1244
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1245
	$error = false;
1246
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1247
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1248
	if ($ldapanon == true) {
1249
		if (!($res = @ldap_bind($ldap))) {
1250
			$error = true;
1251
		}
1252
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1253
		$error = true;
1254
	}
1255

    
1256
	if ($error == true) {
1257
		@ldap_close($ldap);
1258
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1259
		return false;
1260
	}
1261

    
1262
	/* Get LDAP Authcontainers and split em up. */
1263
	$ldac_splits = explode(";", $ldapauthcont);
1264

    
1265
	/* setup the usercount so we think we haven't found anyone yet */
1266
	$usercount = 0;
1267

    
1268
	/*****************************************************************/
1269
	/*  We first find the user based on username and filter          */
1270
	/*  then, once we find the first occurrence of that person       */
1271
	/*  we set session variables to point to the OU and DN of the    */
1272
	/*  person.  To later be used by ldap_get_groups.                */
1273
	/*  that way we don't have to search twice.                      */
1274
	/*****************************************************************/
1275
	if ($debug) {
1276
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1277
	}
1278
	/* Iterate through the user containers for search */
1279
	foreach ($ldac_splits as $i => $ldac_split) {
1280
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1281
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1282
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1283
		/* Make sure we just use the first user we find */
1284
		if ($debug) {
1285
			log_auth(sprintf(gettext('Now Searching in server %1$s, container %2$s with filter %3$s.'), $ldapname, utf8_decode($ldac_split), utf8_decode($ldapfilter)));
1286
		}
1287
		if ($ldapscope == "one") {
1288
			$ldapfunc = "ldap_list";
1289
		} else {
1290
			$ldapfunc = "ldap_search";
1291
		}
1292
		/* Support legacy auth container specification. */
1293
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1294
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1295
		} else {
1296
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1297
		}
1298
		if (!$search) {
1299
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1300
			continue;
1301
		}
1302
		$info = ldap_get_entries($ldap, $search);
1303
		$matches = $info['count'];
1304
		if ($matches == 1) {
1305
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1306
			$_SESSION['ldapou'] = $ldac_split[$i];
1307
			$_SESSION['ldapon'] = "true";
1308
			$usercount = 1;
1309
			break;
1310
		}
1311
	}
1312

    
1313
	if ($usercount != 1) {
1314
		@ldap_unbind($ldap);
1315
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1316
		return false;
1317
	}
1318

    
1319
	/* Now lets bind as the user we found */
1320
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1321
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1322
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1323
		@ldap_unbind($ldap);
1324
		return false;
1325
	}
1326

    
1327
	if ($debug) {
1328
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1329
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1330
	}
1331

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

    
1335
	return true;
1336
}
1337

    
1338
function radius_backed($username, $passwd, $authcfg, &$attributes = array()) {
1339
	global $debug, $config;
1340
	$ret = false;
1341

    
1342
	require_once("radius.inc");
1343

    
1344
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1345
	if ($authcfg) {
1346
		$radiusservers = array();
1347
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1348
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1349
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1350
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1351
	} else {
1352
		return false;
1353
	}
1354

    
1355
	/* Add new servers to our instance */
1356
	foreach ($radiusservers as $radsrv) {
1357
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1358
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1359
	}
1360

    
1361
	if (PEAR::isError($rauth->start())) {
1362
		$retvalue['auth_val'] = 1;
1363
		$retvalue['error'] = $rauth->getError();
1364
		if ($debug) {
1365
			printf(gettext("Radius start: %s<br />\n"), $retvalue['error']);
1366
		}
1367
	}
1368

    
1369
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1370

    
1371
	/* Send request */
1372
	$result = $rauth->send();
1373
	if (PEAR::isError($result)) {
1374
		$retvalue['auth_val'] = 1;
1375
		$retvalue['error'] = $result->getMessage();
1376
		if ($debug) {
1377
			printf(gettext("Radius send failed: %s<br />\n"), $retvalue['error']);
1378
		}
1379
	} else if ($result === true) {
1380
		if ($rauth->getAttributes()) {
1381
			$attributes = $rauth->listAttributes();
1382
		}
1383
		$retvalue['auth_val'] = 2;
1384
		if ($debug) {
1385
			printf(gettext("Radius Auth succeeded")."<br />\n");
1386
		}
1387
		$ret = true;
1388
	} else {
1389
		$retvalue['auth_val'] = 3;
1390
		if ($debug) {
1391
			printf(gettext("Radius Auth rejected")."<br />\n");
1392
		}
1393
	}
1394

    
1395
	// close OO RADIUS_AUTHENTICATION
1396
	$rauth->close();
1397

    
1398
	return $ret;
1399
}
1400

    
1401
/*
1402
	$attributes must contain a "class" key containing the groups and local
1403
	groups must exist to match.
1404
*/
1405
function radius_get_groups($attributes) {
1406
	$groups = array();
1407
	if (!empty($attributes) && is_array($attributes) && !empty($attributes['class'])) {
1408
		$groups = explode(";", $attributes['class']);
1409
		foreach ($groups as & $grp) {
1410
			$grp = trim($grp);
1411
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1412
				$grp = substr($grp, 3);
1413
			}
1414
		}
1415
	}
1416
	return $groups;
1417
}
1418

    
1419
function get_user_expiration_date($username) {
1420
	$user = getUserEntry($username);
1421
	if ($user['expires']) {
1422
		return $user['expires'];
1423
	}
1424
}
1425

    
1426
function is_account_expired($username) {
1427
	$expirydate = get_user_expiration_date($username);
1428
	if ($expirydate) {
1429
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1430
			return true;
1431
		}
1432
	}
1433

    
1434
	return false;
1435
}
1436

    
1437
function is_account_disabled($username) {
1438
	$user = getUserEntry($username);
1439
	if (isset($user['disabled'])) {
1440
		return true;
1441
	}
1442

    
1443
	return false;
1444
}
1445

    
1446
function auth_get_authserver($name) {
1447
	global $config;
1448

    
1449
	if (is_array($config['system']['authserver'])) {
1450
		foreach ($config['system']['authserver'] as $authcfg) {
1451
			if ($authcfg['name'] == $name) {
1452
				return $authcfg;
1453
			}
1454
		}
1455
	}
1456
	if ($name == "Local Database") {
1457
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1458
	}
1459
}
1460

    
1461
function auth_get_authserver_list() {
1462
	global $config;
1463

    
1464
	$list = array();
1465

    
1466
	if (is_array($config['system']['authserver'])) {
1467
		foreach ($config['system']['authserver'] as $authcfg) {
1468
			/* Add support for disabled entries? */
1469
			$list[$authcfg['name']] = $authcfg;
1470
		}
1471
	}
1472

    
1473
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1474
	return $list;
1475
}
1476

    
1477
function getUserGroups($username, $authcfg, &$attributes = array()) {
1478
	global $config;
1479

    
1480
	$allowed_groups = array();
1481

    
1482
	switch ($authcfg['type']) {
1483
		case 'ldap':
1484
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1485
			break;
1486
		case 'radius':
1487
			$allowed_groups = @radius_get_groups($attributes);
1488
			break;
1489
		default:
1490
			$user = getUserEntry($username);
1491
			$allowed_groups = @local_user_get_groups($user, true);
1492
			break;
1493
	}
1494

    
1495
	$member_groups = array();
1496
	if (is_array($config['system']['group'])) {
1497
		foreach ($config['system']['group'] as $group) {
1498
			if (in_array($group['name'], $allowed_groups)) {
1499
				$member_groups[] = $group['name'];
1500
			}
1501
		}
1502
	}
1503

    
1504
	return $member_groups;
1505
}
1506

    
1507
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1508

    
1509
	if (!$authcfg) {
1510
		return local_backed($username, $password);
1511
	}
1512

    
1513
	$authenticated = false;
1514
	switch ($authcfg['type']) {
1515
		case 'ldap':
1516
			if (ldap_backed($username, $password, $authcfg)) {
1517
				$authenticated = true;
1518
			}
1519
			break;
1520
		case 'radius':
1521
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1522
				$authenticated = true;
1523
			}
1524
			break;
1525
		default:
1526
			/* lookup user object by name */
1527
			if (local_backed($username, $password)) {
1528
				$authenticated = true;
1529
			}
1530
			break;
1531
		}
1532

    
1533
	return $authenticated;
1534
}
1535

    
1536
function session_auth() {
1537
	global $config, $_SESSION, $page;
1538

    
1539
	// Handle HTTPS httponly and secure flags
1540
	$currentCookieParams = session_get_cookie_params();
1541
	session_set_cookie_params(
1542
		$currentCookieParams["lifetime"],
1543
		$currentCookieParams["path"],
1544
		NULL,
1545
		($config['system']['webgui']['protocol'] == "https"),
1546
		true
1547
	);
1548

    
1549
	if (!session_id()) {
1550
		session_start();
1551
	}
1552

    
1553
	// Detect protocol change
1554
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1555
		return false;
1556
	}
1557

    
1558
	/* Validate incoming login request */
1559
	$attributes = array();
1560
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1561
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1562
		if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes) ||
1563
		    authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1564
			// Generate a new id to avoid session fixation
1565
			session_regenerate_id();
1566
			$_SESSION['Logged_In'] = "True";
1567
			$_SESSION['Username'] = $_POST['usernamefld'];
1568
			$_SESSION['user_radius_attributes'] = $attributes;
1569
			$_SESSION['last_access'] = time();
1570
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1571
			if (!isset($config['system']['webgui']['quietlogin'])) {
1572
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1573
			}
1574
			if (isset($_POST['postafterlogin'])) {
1575
				return true;
1576
			} else {
1577
				if (empty($page)) {
1578
					$page = "/";
1579
				}
1580
				header("Location: {$page}");
1581
			}
1582
			exit;
1583
		} else {
1584
			/* give the user an error message */
1585
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1586
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1587
			if (isAjax()) {
1588
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1589
				return;
1590
			}
1591
		}
1592
	}
1593

    
1594
	/* Show login page if they aren't logged in */
1595
	if (empty($_SESSION['Logged_In'])) {
1596
		return false;
1597
	}
1598

    
1599
	/* If session timeout isn't set, we don't mark sessions stale */
1600
	if (!isset($config['system']['webgui']['session_timeout'])) {
1601
		/* Default to 4 hour timeout if one is not set */
1602
		if ($_SESSION['last_access'] < (time() - 14400)) {
1603
			$_GET['logout'] = true;
1604
			$_SESSION['Logout'] = true;
1605
		} else {
1606
			$_SESSION['last_access'] = time();
1607
		}
1608
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1609
		/* only update if it wasn't ajax */
1610
		if (!isAjax()) {
1611
			$_SESSION['last_access'] = time();
1612
		}
1613
	} else {
1614
		/* Check for stale session */
1615
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1616
			$_GET['logout'] = true;
1617
			$_SESSION['Logout'] = true;
1618
		} else {
1619
			/* only update if it wasn't ajax */
1620
			if (!isAjax()) {
1621
				$_SESSION['last_access'] = time();
1622
			}
1623
		}
1624
	}
1625

    
1626
	/* user hit the logout button */
1627
	if (isset($_GET['logout'])) {
1628

    
1629
		if ($_SESSION['Logout']) {
1630
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1631
		} else {
1632
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1633
		}
1634

    
1635
		/* wipe out $_SESSION */
1636
		$_SESSION = array();
1637

    
1638
		if (isset($_COOKIE[session_name()])) {
1639
			setcookie(session_name(), '', time()-42000, '/');
1640
		}
1641

    
1642
		/* and destroy it */
1643
		session_destroy();
1644

    
1645
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1646
		$scriptElms = count($scriptName);
1647
		$scriptName = $scriptName[$scriptElms-1];
1648

    
1649
		if (isAjax()) {
1650
			return false;
1651
		}
1652

    
1653
		/* redirect to page the user is on, it'll prompt them to login again */
1654
		header("Location: {$scriptName}");
1655

    
1656
		return false;
1657
	}
1658

    
1659
	/*
1660
	 * this is for debugging purpose if you do not want to use Ajax
1661
	 * to submit a HTML form. It basically disables the observation
1662
	 * of the submit event and hence does not trigger Ajax.
1663
	 */
1664
	if ($_GET['disable_ajax']) {
1665
		$_SESSION['NO_AJAX'] = "True";
1666
	}
1667

    
1668
	/*
1669
	 * Same to re-enable Ajax.
1670
	 */
1671
	if ($_GET['enable_ajax']) {
1672
		unset($_SESSION['NO_AJAX']);
1673
	}
1674

    
1675
	return true;
1676
}
1677

    
1678
?>
(4-4/65)