Project

General

Profile

Download (49.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * auth.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>
7
 * Copyright (c) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 * Copyright (c) 2006 Paul Taylor <paultaylor@winn-dixie.com>
9
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

    
25
/*
26
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
27
 * file courtesy of Michael Retterklieber.
28
 */
29
if (!$do_not_include_config_gui_inc) {
30
	require_once("config.gui.inc");
31
}
32

    
33
// Will be changed to false if security checks fail
34
$security_passed = true;
35

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

    
42
	/* Either a IPv6 address with or without a alternate port */
43
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
44
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
45
		/* v6 address has more parts, drop the last part */
46
		if (count($http_host_port) > 1) {
47
			array_pop($http_host_port);
48
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
49
		} else {
50
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
51
		}
52
	} else {
53
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
54
		$http_host = $http_host[0];
55
	}
56
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
57
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
58
		$found_host = true;
59
	}
60
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
61
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
62
		$found_host = true;
63
	}
64

    
65
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
66
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
67
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
68
				$found_host = true;
69
				break;
70
			}
71
		}
72
	}
73

    
74
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
75
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
76
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
77
				$found_host = true;
78
				break;
79
			}
80
		}
81
	}
82

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

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

    
102
// If the HTTP_REFERER is something other than ourselves then disallow.
103
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
104
	if ($_SERVER['HTTP_REFERER']) {
105
		if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
106
			if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
107
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
108
				header("Refresh: 1; url=index.php");
109
?>
110
<!DOCTYPE html>
111
<html lang="en">
112
<head>
113
	<link rel="stylesheet" href="/css/pfSense.css" />
114
	<title><?=gettext("Redirecting..."); ?></title>
115
</head>
116
<body id="error" class="no-menu">
117
	<div id="jumbotron">
118
		<div class="container">
119
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
120
				<p><?=gettext("Redirecting to the dashboard...")?></p>
121
			</div>
122
		</div>
123
	</div>
124
</body>
125
</html>
126
<?php
127
				exit;
128
			}
129
		}
130
		$found_host = false;
131
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
132
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
133
		if ($referrer_host) {
134
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
135
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
136
				$found_host = true;
137
			}
138

    
139
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
140
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
141
				foreach ($althosts as $ah) {
142
					if (strcasecmp($referrer_host, $ah) == 0) {
143
						$found_host = true;
144
						break;
145
					}
146
				}
147
			}
148

    
149
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
150
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
151
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
152
						$found_host = true;
153
						break;
154
					}
155
				}
156
			}
157

    
158
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
159
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
160
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
161
						$found_host = true;
162
						break;
163
					}
164
				}
165
			}
166

    
167
			if (!$found_host) {
168
				$interface_list_ips = get_configured_ip_addresses();
169
				foreach ($interface_list_ips as $ilips) {
170
					if (strcasecmp($referrer_host, $ilips) == 0) {
171
						$found_host = true;
172
						break;
173
					}
174
				}
175
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
176
				foreach ($interface_list_ipv6s as $ilipv6s) {
177
					$ilipv6s = explode('%', $ilipv6s)[0];
178
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
179
						$found_host = true;
180
						break;
181
					}
182
				}
183
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
184
					// allow SSH port forwarded connections and links from localhost
185
					$found_host = true;
186
				}
187
			}
188
		}
189
		if ($found_host == false) {
190
			if (!security_checks_disabled()) {
191
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  If not needed, this check can be disabled in System -> Advanced -> Admin.");
192
				exit;
193
			}
194
			$security_passed = false;
195
		}
196
	} else {
197
		$security_passed = false;
198
	}
199
}
200

    
201
if (function_exists("display_error_form") && $security_passed) {
202
	/* Security checks passed, so it should be OK to turn them back on */
203
	restore_security_checks();
204
}
205
unset($security_passed);
206

    
207
$groupindex = index_groups();
208
$userindex = index_users();
209

    
210
function index_groups() {
211
	global $g, $debug, $config, $groupindex;
212

    
213
	$groupindex = array();
214

    
215
	if (is_array($config['system']['group'])) {
216
		$i = 0;
217
		foreach ($config['system']['group'] as $groupent) {
218
			$groupindex[$groupent['name']] = $i;
219
			$i++;
220
		}
221
	}
222

    
223
	return ($groupindex);
224
}
225

    
226
function index_users() {
227
	global $g, $debug, $config;
228

    
229
	if (is_array($config['system']['user'])) {
230
		$i = 0;
231
		foreach ($config['system']['user'] as $userent) {
232
			$userindex[$userent['name']] = $i;
233
			$i++;
234
		}
235
	}
236

    
237
	return ($userindex);
238
}
239

    
240
function & getUserEntry($name) {
241
	global $debug, $config, $userindex;
242
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
243

    
244
	if (isset($userindex[$name])) {
245
		return $config['system']['user'][$userindex[$name]];
246
	} elseif ($authcfg['type'] != "Local Database") {
247
		$user = array();
248
		$user['name'] = $name;
249
		return $user;
250
	}
251
}
252

    
253
function & getUserEntryByUID($uid) {
254
	global $debug, $config;
255

    
256
	if (is_array($config['system']['user'])) {
257
		foreach ($config['system']['user'] as & $user) {
258
			if ($user['uid'] == $uid) {
259
				return $user;
260
			}
261
		}
262
	}
263

    
264
	return false;
265
}
266

    
267
function & getGroupEntry($name) {
268
	global $debug, $config, $groupindex;
269
	if (isset($groupindex[$name])) {
270
		return $config['system']['group'][$groupindex[$name]];
271
	}
272
}
273

    
274
function & getGroupEntryByGID($gid) {
275
	global $debug, $config;
276

    
277
	if (is_array($config['system']['group'])) {
278
		foreach ($config['system']['group'] as & $group) {
279
			if ($group['gid'] == $gid) {
280
				return $group;
281
			}
282
		}
283
	}
284

    
285
	return false;
286
}
287

    
288
function get_user_privileges(& $user) {
289
	global $config;
290

    
291
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
292
	$names = array();
293

    
294
	$privs = $user['priv'];
295
	if (!is_array($privs)) {
296
		$privs = array();
297
	}
298

    
299
	if ($authcfg['type'] == "ldap") {
300
		$names = @ldap_get_groups($user['name'], $authcfg);
301
	} elseif ($authcfg['type'] == "radius") {
302
		$names = @radius_get_groups($_SESSION['user_radius_attributes']);
303
	}
304

    
305
	if (empty($names)) {
306
		$names = local_user_get_groups($user, true);
307
	}
308

    
309
	foreach ($names as $name) {
310
		$group = getGroupEntry($name);
311
		if (is_array($group['priv'])) {
312
			$privs = array_merge($privs, $group['priv']);
313
		}
314
	}
315

    
316
	return $privs;
317
}
318

    
319
function userHasPrivilege($userent, $privid = false) {
320

    
321
	if (!$privid || !is_array($userent)) {
322
		return false;
323
	}
324

    
325
	$privs = get_user_privileges($userent);
326

    
327
	if (!is_array($privs)) {
328
		return false;
329
	}
330

    
331
	if (!in_array($privid, $privs)) {
332
		return false;
333
	}
334

    
335
	return true;
336
}
337

    
338
function local_backed($username, $passwd) {
339

    
340
	$user = getUserEntry($username);
341
	if (!$user) {
342
		return false;
343
	}
344

    
345
	if (is_account_disabled($username) || is_account_expired($username)) {
346
		return false;
347
	}
348

    
349
	if ($user['bcrypt-hash']) {
350
		if (password_verify($passwd, $user['bcrypt-hash'])) {
351
			return true;
352
		}
353
	}
354

    
355
	//for backwards compatibility
356
	if ($user['password']) {
357
		if (crypt($passwd, $user['password']) == $user['password']) {
358
			return true;
359
		}
360
	}
361

    
362
	if ($user['md5-hash']) {
363
		if (md5($passwd) == $user['md5-hash']) {
364
			return true;
365
		}
366
	}
367

    
368
	return false;
369
}
370

    
371
function local_sync_accounts() {
372
	global $debug, $config;
373

    
374
	/* remove local users to avoid uid conflicts */
375
	$fd = popen("/usr/sbin/pw usershow -a", "r");
376
	if ($fd) {
377
		while (!feof($fd)) {
378
			$line = explode(":", fgets($fd));
379
			if ($line[0] != "admin") {
380
				if (!strncmp($line[0], "_", 1)) {
381
					continue;
382
				}
383
				if ($line[2] < 2000) {
384
					continue;
385
				}
386
				if ($line[2] > 65000) {
387
					continue;
388
				}
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 " . escapeshellarg($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 -g " . escapeshellarg($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

    
447
}
448

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

    
452
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
453
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
454
		return;
455
	}
456

    
457

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

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

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

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

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

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

    
516
	$skel_dir = '/etc/skel';
517

    
518
	/* determine add or mod */
519
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
520
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
521
	} else {
522
		$user_op = "usermod";
523
	}
524

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

    
536
	if ($debug) {
537
		log_error(sprintf(gettext("Running: %s"), $cmd));
538
	}
539
	$fd = popen($cmd, "w");
540
	if (empty($user['bcrypt-hash'])) {
541
		fwrite($fd, $user['password']);
542
	} else {
543
		fwrite($fd, $user['bcrypt-hash']);
544
	}
545
	pclose($fd);
546

    
547
	/* create user directory if required */
548
	if (!is_dir($user_home)) {
549
		mkdir($user_home, 0700);
550
	}
551
	@chown($user_home, $user_name);
552
	@chgrp($user_home, $user_group);
553

    
554
	/* Make sure all users have last version of config files */
555
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
556
		$target = $user_home . '/' . substr(basename($dot_file), 3);
557
		@copy($dot_file, $target);
558
		@chown($target, $user_name);
559
		@chgrp($target, $user_group);
560
	}
561

    
562
	/* write out ssh authorized key file */
563
	if ($user['authorizedkeys']) {
564
		if (!is_dir("{$user_home}/.ssh")) {
565
			@mkdir("{$user_home}/.ssh", 0700);
566
			@chown("{$user_home}/.ssh", $user_name);
567
		}
568
		$keys = base64_decode($user['authorizedkeys']);
569
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
570
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
571
	} else {
572
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
573
	}
574

    
575
	$un = $lock_account ? "" : "un";
576
	exec("/usr/sbin/pw {$un}lock " . escapeshellarg($user_name) . " -q 2>/dev/null");
577

    
578
}
579

    
580
function local_user_del($user) {
581
	global $debug;
582

    
583
	/* remove all memberships */
584
	local_user_set_groups($user);
585

    
586
	/* Don't remove /root */
587
	if ($user['uid'] != 0) {
588
		$rmhome = "-r";
589
	}
590

    
591
	/* read from pw db */
592
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
593
	$pwread = fgets($fd);
594
	pclose($fd);
595
	$userattrs = explode(":", trim($pwread));
596

    
597
	if ($userattrs[0] != $user['name']) {
598
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
599
		return;
600
	}
601

    
602
	/* delete from pw db */
603
	$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($user['name']) . " " . escapeshellarg($rmhome);
604

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

    
610
	/* Delete user from groups needs a call to write_config() */
611
	local_group_del_user($user);
612
}
613

    
614
function local_user_set_password(&$user, $password) {
615

    
616
	unset($user['password']);
617
	unset($user['md5-hash']);
618
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
619

    
620
	/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
621
	 * https://reviews.freebsd.org/D2742
622
	 * XXX: Can be removed as soon as r284483 is MFC'd.
623
	 */
624
	if ($user['bcrypt-hash'][2] == "y") {
625
		$user['bcrypt-hash'][2] = "b";
626
	}
627

    
628
	// Converts ascii to unicode.
629
	$astr = (string) $password;
630
	$ustr = '';
631
	for ($i = 0; $i < strlen($astr); $i++) {
632
		$a = ord($astr{$i}) << 8;
633
		$ustr .= sprintf("%X", $a);
634
	}
635

    
636
}
637

    
638
function local_user_get_groups($user, $all = false) {
639
	global $debug, $config;
640

    
641
	$groups = array();
642
	if (!is_array($config['system']['group'])) {
643
		return $groups;
644
	}
645

    
646
	foreach ($config['system']['group'] as $group) {
647
		if ($all || (!$all && ($group['name'] != "all"))) {
648
			if (is_array($group['member'])) {
649
				if (in_array($user['uid'], $group['member'])) {
650
					$groups[] = $group['name'];
651
				}
652
			}
653
		}
654
	}
655

    
656
	if ($all) {
657
		$groups[] = "all";
658
	}
659

    
660
	sort($groups);
661

    
662
	return $groups;
663

    
664
}
665

    
666
function local_user_set_groups($user, $new_groups = NULL) {
667
	global $debug, $config, $groupindex;
668

    
669
	if (!is_array($config['system']['group'])) {
670
		return;
671
	}
672

    
673
	$cur_groups = local_user_get_groups($user, true);
674
	$mod_groups = array();
675

    
676
	if (!is_array($new_groups)) {
677
		$new_groups = array();
678
	}
679

    
680
	if (!is_array($cur_groups)) {
681
		$cur_groups = array();
682
	}
683

    
684
	/* determine which memberships to add */
685
	foreach ($new_groups as $groupname) {
686
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
687
			continue;
688
		}
689
		$group = & $config['system']['group'][$groupindex[$groupname]];
690
		$group['member'][] = $user['uid'];
691
		$mod_groups[] = $group;
692
	}
693
	unset($group);
694

    
695
	/* determine which memberships to remove */
696
	foreach ($cur_groups as $groupname) {
697
		if (in_array($groupname, $new_groups)) {
698
			continue;
699
		}
700
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
701
			continue;
702
		}
703
		$group = & $config['system']['group'][$groupindex[$groupname]];
704
		if (is_array($group['member'])) {
705
			$index = array_search($user['uid'], $group['member']);
706
			array_splice($group['member'], $index, 1);
707
			$mod_groups[] = $group;
708
		}
709
	}
710
	unset($group);
711

    
712
	/* sync all modified groups */
713
	foreach ($mod_groups as $group) {
714
		local_group_set($group);
715
	}
716
}
717

    
718
function local_group_del_user($user) {
719
	global $config;
720

    
721
	if (!is_array($config['system']['group'])) {
722
		return;
723
	}
724

    
725
	foreach ($config['system']['group'] as $group) {
726
		if (is_array($group['member'])) {
727
			foreach ($group['member'] as $idx => $uid) {
728
				if ($user['uid'] == $uid) {
729
					unset($config['system']['group']['member'][$idx]);
730
				}
731
			}
732
		}
733
	}
734
}
735

    
736
function local_group_set($group, $reset = false) {
737
	global $debug;
738

    
739
	$group_name = $group['name'];
740
	$group_gid = $group['gid'];
741
	$group_members = '';
742
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
743
		$group_members = implode(",", $group['member']);
744
	}
745

    
746
	if (empty($group_name) || $group['scope'] == "remote") {
747
		return;
748
	}
749

    
750
	/* determine add or mod */
751
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
752
		$group_op = "groupmod -l";
753
	} else {
754
		$group_op = "groupadd -n";
755
	}
756

    
757
	/* add or mod group db */
758
	$cmd = "/usr/sbin/pw {$group_op} " .
759
		escapeshellarg($group_name) .
760
		" -g " . escapeshellarg($group_gid) .
761
		" -M " . escapeshellarg($group_members) . " 2>&1";
762

    
763
	if ($debug) {
764
		log_error(sprintf(gettext("Running: %s"), $cmd));
765
	}
766
	mwexec($cmd);
767

    
768
}
769

    
770
function local_group_del($group) {
771
	global $debug;
772

    
773
	/* delete from group db */
774
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
775

    
776
	if ($debug) {
777
		log_error(sprintf(gettext("Running: %s"), $cmd));
778
	}
779
	mwexec($cmd);
780
}
781

    
782
function ldap_test_connection($authcfg) {
783
	global $debug, $config, $g;
784

    
785
	if ($authcfg) {
786
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
787
			$ldapproto = "ldap";
788
		} else {
789
			$ldapproto = "ldaps";
790
		}
791
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
792
		$ldapport = $authcfg['ldap_port'];
793
		if (!empty($ldapport)) {
794
			$ldapserver .= ":{$ldapport}";
795
		}
796
		$ldapbasedn = $authcfg['ldap_basedn'];
797
		$ldapbindun = $authcfg['ldap_binddn'];
798
		$ldapbindpw = $authcfg['ldap_bindpw'];
799
	} else {
800
		return false;
801
	}
802

    
803
	/* first check if there is even an LDAP server populated */
804
	if (!$ldapserver) {
805
		return false;
806
	}
807

    
808
	/* Setup CA environment if needed. */
809
	ldap_setup_caenv($authcfg);
810

    
811
	/* connect and see if server is up */
812
	$error = false;
813
	if (!($ldap = ldap_connect($ldapserver))) {
814
		$error = true;
815
	}
816

    
817
	if ($error == true) {
818
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
819
		return false;
820
	}
821

    
822
	return true;
823
}
824

    
825
function ldap_setup_caenv($authcfg) {
826
	global $g;
827
	require_once("certs.inc");
828

    
829
	unset($caref);
830
	if (empty($authcfg['ldap_caref']) || !strstr($authcfg['ldap_urltype'], "SSL")) {
831
		putenv('LDAPTLS_REQCERT=never');
832
		return;
833
	} else {
834
		$caref = lookup_ca($authcfg['ldap_caref']);
835
		if (!$caref) {
836
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
837
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
838
			putenv('LDAPTLS_REQCERT=hard');
839
			return;
840
		}
841
		if (!is_dir("{$g['varrun_path']}/certs")) {
842
			@mkdir("{$g['varrun_path']}/certs");
843
		}
844
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
845
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
846
		}
847
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", base64_decode($caref['crt']));
848
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
849
		putenv('LDAPTLS_REQCERT=hard');
850
		/* XXX: Probably even the hashed link should be created for this? */
851
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
852
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
853
	}
854
}
855

    
856
function ldap_test_bind($authcfg) {
857
	global $debug, $config, $g;
858

    
859
	if ($authcfg) {
860
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
861
			$ldapproto = "ldap";
862
		} else {
863
			$ldapproto = "ldaps";
864
		}
865
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
866
		$ldapport = $authcfg['ldap_port'];
867
		if (!empty($ldapport)) {
868
			$ldapserver .= ":{$ldapport}";
869
		}
870
		$ldapbasedn = $authcfg['ldap_basedn'];
871
		$ldapbindun = $authcfg['ldap_binddn'];
872
		$ldapbindpw = $authcfg['ldap_bindpw'];
873
		$ldapver = $authcfg['ldap_protver'];
874
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
875
		if (empty($ldapbndun) || empty($ldapbindpw)) {
876
			$ldapanon = true;
877
		} else {
878
			$ldapanon = false;
879
		}
880
	} else {
881
		return false;
882
	}
883

    
884
	/* first check if there is even an LDAP server populated */
885
	if (!$ldapserver) {
886
		return false;
887
	}
888

    
889
	/* Setup CA environment if needed. */
890
	ldap_setup_caenv($authcfg);
891

    
892
	/* connect and see if server is up */
893
	$error = false;
894
	if (!($ldap = ldap_connect($ldapserver))) {
895
		$error = true;
896
	}
897

    
898
	if ($error == true) {
899
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
900
		return false;
901
	}
902

    
903
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
904
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
905
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
906
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
907
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
908

    
909
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
910
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
911
	if ($ldapanon == true) {
912
		if (!($res = @ldap_bind($ldap))) {
913
			@ldap_close($ldap);
914
			return false;
915
		}
916
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
917
		@ldap_close($ldap);
918
		return false;
919
	}
920

    
921
	@ldap_unbind($ldap);
922

    
923
	return true;
924
}
925

    
926
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
927
	global $debug, $config, $g;
928

    
929
	if (!function_exists("ldap_connect")) {
930
		return;
931
	}
932

    
933
	$ous = array();
934

    
935
	if ($authcfg) {
936
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
937
			$ldapproto = "ldap";
938
		} else {
939
			$ldapproto = "ldaps";
940
		}
941
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
942
		$ldapport = $authcfg['ldap_port'];
943
		if (!empty($ldapport)) {
944
			$ldapserver .= ":{$ldapport}";
945
		}
946
		$ldapbasedn = $authcfg['ldap_basedn'];
947
		$ldapbindun = $authcfg['ldap_binddn'];
948
		$ldapbindpw = $authcfg['ldap_bindpw'];
949
		$ldapver = $authcfg['ldap_protver'];
950
		if (empty($ldapbindun) || empty($ldapbindpw)) {
951
			$ldapanon = true;
952
		} else {
953
			$ldapanon = false;
954
		}
955
		$ldapname = $authcfg['name'];
956
		$ldapfallback = false;
957
		$ldapscope = $authcfg['ldap_scope'];
958
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
959
	} else {
960
		return false;
961
	}
962

    
963
	/* first check if there is even an LDAP server populated */
964
	if (!$ldapserver) {
965
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
966
		return $ous;
967
	}
968

    
969
	/* Setup CA environment if needed. */
970
	ldap_setup_caenv($authcfg);
971

    
972
	/* connect and see if server is up */
973
	$error = false;
974
	if (!($ldap = ldap_connect($ldapserver))) {
975
		$error = true;
976
	}
977

    
978
	if ($error == true) {
979
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
980
		return $ous;
981
	}
982

    
983
	$ldapfilter = "(|(ou=*)(cn=Users))";
984

    
985
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
986
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
987
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
988
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
989
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
990

    
991
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
992
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
993
	if ($ldapanon == true) {
994
		if (!($res = @ldap_bind($ldap))) {
995
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
996
			@ldap_close($ldap);
997
			return $ous;
998
		}
999
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1000
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1001
		@ldap_close($ldap);
1002
		return $ous;
1003
	}
1004

    
1005
	if ($ldapscope == "one") {
1006
		$ldapfunc = "ldap_list";
1007
	} else {
1008
		$ldapfunc = "ldap_search";
1009
	}
1010

    
1011
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1012
	$info = @ldap_get_entries($ldap, $search);
1013

    
1014
	if (is_array($info)) {
1015
		foreach ($info as $inf) {
1016
			if (!$show_complete_ou) {
1017
				$inf_split = explode(",", $inf['dn']);
1018
				$ou = $inf_split[0];
1019
				$ou = str_replace("OU=", "", $ou);
1020
				$ou = str_replace("CN=", "", $ou);
1021
			} else {
1022
				if ($inf['dn']) {
1023
					$ou = $inf['dn'];
1024
				}
1025
			}
1026
			if ($ou) {
1027
				$ous[] = $ou;
1028
			}
1029
		}
1030
	}
1031

    
1032
	@ldap_unbind($ldap);
1033

    
1034
	return $ous;
1035
}
1036

    
1037
function ldap_get_groups($username, $authcfg) {
1038
	global $debug, $config;
1039

    
1040
	if (!function_exists("ldap_connect")) {
1041
		return;
1042
	}
1043

    
1044
	if (!$username) {
1045
		return false;
1046
	}
1047

    
1048
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1049
		$username_split = explode("@", $username);
1050
		$username = $username_split[0];
1051
	}
1052

    
1053
	if (stristr($username, "\\")) {
1054
		$username_split = explode("\\", $username);
1055
		$username = $username_split[0];
1056
	}
1057

    
1058
	//log_error("Getting LDAP groups for {$username}.");
1059
	if ($authcfg) {
1060
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
1061
			$ldapproto = "ldap";
1062
		} else {
1063
			$ldapproto = "ldaps";
1064
		}
1065
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1066
		$ldapport = $authcfg['ldap_port'];
1067
		if (!empty($ldapport)) {
1068
			$ldapserver .= ":{$ldapport}";
1069
		}
1070
		$ldapbasedn = $authcfg['ldap_basedn'];
1071
		$ldapbindun = $authcfg['ldap_binddn'];
1072
		$ldapbindpw = $authcfg['ldap_bindpw'];
1073
		$ldapauthcont = $authcfg['ldap_authcn'];
1074
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1075
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1076
		if (isset($authcfg['ldap_rfc2307'])) {
1077
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1078
		} else {
1079
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1080
		}
1081
		$ldaptype = "";
1082
		$ldapver = $authcfg['ldap_protver'];
1083
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1084
			$ldapanon = true;
1085
		} else {
1086
			$ldapanon = false;
1087
		}
1088
		$ldapname = $authcfg['name'];
1089
		$ldapfallback = false;
1090
		$ldapscope = $authcfg['ldap_scope'];
1091
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1092
	} else {
1093
		return false;
1094
	}
1095

    
1096
	if (isset($authcfg['ldap_rfc2307'])) {
1097
		$ldapdn = $ldapbasedn;
1098
	} else {
1099
		$ldapdn = $_SESSION['ldapdn'];
1100
	}
1101

    
1102
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1103
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1104
	$memberof = array();
1105

    
1106
	/* Setup CA environment if needed. */
1107
	ldap_setup_caenv($authcfg);
1108

    
1109
	/* connect and see if server is up */
1110
	$error = false;
1111
	if (!($ldap = ldap_connect($ldapserver))) {
1112
		$error = true;
1113
	}
1114

    
1115
	if ($error == true) {
1116
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1117
		return memberof;
1118
	}
1119

    
1120
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1121
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1122
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1123
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1124
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1125

    
1126
	/* bind as user that has rights to read group attributes */
1127
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1128
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1129
	if ($ldapanon == true) {
1130
		if (!($res = @ldap_bind($ldap))) {
1131
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1132
			@ldap_close($ldap);
1133
			return false;
1134
		}
1135
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1136
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1137
		@ldap_close($ldap);
1138
		return memberof;
1139
	}
1140

    
1141
	/* get groups from DN found */
1142
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1143
	/* since we know the DN is in $_SESSION['ldapdn'] */
1144
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1145
	if ($ldapscope == "one") {
1146
		$ldapfunc = "ldap_list";
1147
	} else {
1148
		$ldapfunc = "ldap_search";
1149
	}
1150

    
1151
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1152
	$info = @ldap_get_entries($ldap, $search);
1153

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

    
1156
	if (is_array($gresults)) {
1157
		/* Iterate through the groups and throw them into an array */
1158
		foreach ($gresults as $grp) {
1159
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1160
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1161
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1162
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1163
			}
1164
		}
1165
	}
1166

    
1167
	/* Time to close LDAP connection */
1168
	@ldap_unbind($ldap);
1169

    
1170
	$groups = print_r($memberof, true);
1171

    
1172
	//log_error("Returning groups ".$groups." for user $username");
1173

    
1174
	return $memberof;
1175
}
1176

    
1177
function ldap_format_host($host) {
1178
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1179
}
1180

    
1181
function ldap_backed($username, $passwd, $authcfg) {
1182
	global $debug, $config;
1183

    
1184
	if (!$username) {
1185
		return;
1186
	}
1187

    
1188
	if (!function_exists("ldap_connect")) {
1189
		return;
1190
	}
1191

    
1192
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1193
		$username_split = explode("@", $username);
1194
		$username = $username_split[0];
1195
	}
1196
	if (stristr($username, "\\")) {
1197
		$username_split = explode("\\", $username);
1198
		$username = $username_split[0];
1199
	}
1200

    
1201
	if ($authcfg) {
1202
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
1203
			$ldapproto = "ldap";
1204
		} else {
1205
			$ldapproto = "ldaps";
1206
		}
1207
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1208
		$ldapport = $authcfg['ldap_port'];
1209
		if (!empty($ldapport)) {
1210
			$ldapserver .= ":{$ldapport}";
1211
		}
1212
		$ldapbasedn = $authcfg['ldap_basedn'];
1213
		$ldapbindun = $authcfg['ldap_binddn'];
1214
		$ldapbindpw = $authcfg['ldap_bindpw'];
1215
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1216
			$ldapanon = true;
1217
		} else {
1218
			$ldapanon = false;
1219
		}
1220
		$ldapauthcont = $authcfg['ldap_authcn'];
1221
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1222
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1223
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1224
		$ldapfilter = "";
1225
		if (!$ldapextendedqueryenabled) {
1226
			$ldapfilter = "({$ldapnameattribute}={$username})";
1227
		} else {
1228
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1229
		}
1230
		$ldaptype = "";
1231
		$ldapver = $authcfg['ldap_protver'];
1232
		$ldapname = $authcfg['name'];
1233
		$ldapscope = $authcfg['ldap_scope'];
1234
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1235
	} else {
1236
		return false;
1237
	}
1238

    
1239
	/* first check if there is even an LDAP server populated */
1240
	if (!$ldapserver) {
1241
		if ($ldapfallback) {
1242
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1243
			return local_backed($username, $passwd);
1244
		} else {
1245
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1246
		}
1247

    
1248
		return false;
1249
	}
1250

    
1251
	/* Setup CA environment if needed. */
1252
	ldap_setup_caenv($authcfg);
1253

    
1254
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1255
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1256
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1257
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1258
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1259

    
1260
	/* Make sure we can connect to LDAP */
1261
	$error = false;
1262
	if (!($ldap = ldap_connect($ldapserver))) {
1263
		$error = true;
1264
	}
1265

    
1266
	if ($error == true) {
1267
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1268
		return false;
1269
	}
1270

    
1271
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1272
	$error = false;
1273
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1274
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1275
	if ($ldapanon == true) {
1276
		if (!($res = @ldap_bind($ldap))) {
1277
			$error = true;
1278
		}
1279
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1280
		$error = true;
1281
	}
1282

    
1283
	if ($error == true) {
1284
		@ldap_close($ldap);
1285
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1286
		return false;
1287
	}
1288

    
1289
	/* Get LDAP Authcontainers and split em up. */
1290
	$ldac_splits = explode(";", $ldapauthcont);
1291

    
1292
	/* setup the usercount so we think we haven't found anyone yet */
1293
	$usercount = 0;
1294

    
1295
	/*****************************************************************/
1296
	/*  We first find the user based on username and filter          */
1297
	/*  then, once we find the first occurrence of that person       */
1298
	/*  we set session variables to point to the OU and DN of the    */
1299
	/*  person.  To later be used by ldap_get_groups.                */
1300
	/*  that way we don't have to search twice.                      */
1301
	/*****************************************************************/
1302
	if ($debug) {
1303
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1304
	}
1305
	/* Iterate through the user containers for search */
1306
	foreach ($ldac_splits as $i => $ldac_split) {
1307
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1308
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1309
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1310
		/* Make sure we just use the first user we find */
1311
		if ($debug) {
1312
			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)));
1313
		}
1314
		if ($ldapscope == "one") {
1315
			$ldapfunc = "ldap_list";
1316
		} else {
1317
			$ldapfunc = "ldap_search";
1318
		}
1319
		/* Support legacy auth container specification. */
1320
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1321
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1322
		} else {
1323
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1324
		}
1325
		if (!$search) {
1326
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1327
			continue;
1328
		}
1329
		$info = ldap_get_entries($ldap, $search);
1330
		$matches = $info['count'];
1331
		if ($matches == 1) {
1332
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1333
			$_SESSION['ldapou'] = $ldac_split[$i];
1334
			$_SESSION['ldapon'] = "true";
1335
			$usercount = 1;
1336
			break;
1337
		}
1338
	}
1339

    
1340
	if ($usercount != 1) {
1341
		@ldap_unbind($ldap);
1342
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1343
		return false;
1344
	}
1345

    
1346
	/* Now lets bind as the user we found */
1347
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1348
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1349
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1350
		@ldap_unbind($ldap);
1351
		return false;
1352
	}
1353

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

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

    
1362
	return true;
1363
}
1364

    
1365
function radius_backed($username, $passwd, $authcfg, &$attributes = array()) {
1366
	global $debug, $config;
1367
	$ret = false;
1368

    
1369
	require_once("radius.inc");
1370

    
1371
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1372
	if ($authcfg) {
1373
		$radiusservers = array();
1374
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1375
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1376
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1377
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1378
	} else {
1379
		return false;
1380
	}
1381

    
1382
	/* Add new servers to our instance */
1383
	foreach ($radiusservers as $radsrv) {
1384
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1385
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1386
	}
1387

    
1388
	if (PEAR::isError($rauth->start())) {
1389
		$retvalue['auth_val'] = 1;
1390
		$retvalue['error'] = $rauth->getError();
1391
		if ($debug) {
1392
			printf(gettext("RADIUS start: %s<br />\n"), $retvalue['error']);
1393
		}
1394
	}
1395

    
1396
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1397

    
1398
	/* Send request */
1399
	$result = $rauth->send();
1400
	if (PEAR::isError($result)) {
1401
		$retvalue['auth_val'] = 1;
1402
		$retvalue['error'] = $result->getMessage();
1403
		if ($debug) {
1404
			printf(gettext("RADIUS send failed: %s<br />\n"), $retvalue['error']);
1405
		}
1406
	} else if ($result === true) {
1407
		if ($rauth->getAttributes()) {
1408
			$attributes = $rauth->listAttributes();
1409
		}
1410
		$retvalue['auth_val'] = 2;
1411
		if ($debug) {
1412
			printf(gettext("RADIUS Auth succeeded")."<br />\n");
1413
		}
1414
		$ret = true;
1415
	} else {
1416
		$retvalue['auth_val'] = 3;
1417
		if ($debug) {
1418
			printf(gettext("RADIUS Auth rejected")."<br />\n");
1419
		}
1420
	}
1421

    
1422
	// close OO RADIUS_AUTHENTICATION
1423
	$rauth->close();
1424

    
1425
	return $ret;
1426
}
1427

    
1428
/*
1429
	$attributes must contain a "class" key containing the groups and local
1430
	groups must exist to match.
1431
*/
1432
function radius_get_groups($attributes) {
1433
	$groups = array();
1434
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1435
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1436
		$groups = array();
1437
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1438
			foreach ($attributes['class'] as $class) {
1439
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1440
			}
1441
		}
1442

    
1443
		foreach ($groups as & $grp) {
1444
			$grp = trim($grp);
1445
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1446
				$grp = substr($grp, 3);
1447
			}
1448
		}
1449
	}
1450
	return $groups;
1451
}
1452

    
1453
function get_user_expiration_date($username) {
1454
	$user = getUserEntry($username);
1455
	if ($user['expires']) {
1456
		return $user['expires'];
1457
	}
1458
}
1459

    
1460
function is_account_expired($username) {
1461
	$expirydate = get_user_expiration_date($username);
1462
	if ($expirydate) {
1463
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1464
			return true;
1465
		}
1466
	}
1467

    
1468
	return false;
1469
}
1470

    
1471
function is_account_disabled($username) {
1472
	$user = getUserEntry($username);
1473
	if (isset($user['disabled'])) {
1474
		return true;
1475
	}
1476

    
1477
	return false;
1478
}
1479

    
1480
function get_user_settings($username) {
1481
	global $config;
1482
	$settings = array();
1483
	$settings['widgets'] = $config['widgets'];
1484
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1485
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1486
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1487
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1488
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1489
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1490
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1491
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1492
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1493
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1494
	$user = getUserEntry($username);
1495
	if (isset($user['customsettings'])) {
1496
		$settings['customsettings'] = true;
1497
		if (isset($user['widgets'])) {
1498
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1499
			$settings['widgets'] = $user['widgets'];
1500
		}
1501
		if (isset($user['dashboardcolumns'])) {
1502
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1503
		}
1504
		if (isset($user['webguicss'])) {
1505
			$settings['webgui']['webguicss'] = $user['webguicss'];
1506
		}
1507
		if (isset($user['webguihostnamemenu'])) {
1508
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1509
		}
1510
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1511
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1512
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1513
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1514
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1515
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1516
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1517
	} else {
1518
		$settings['customsettings'] = false;
1519
	}
1520

    
1521
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1522
		$settings['webgui']['dashboardcolumns'] = 2;
1523
	}
1524

    
1525
	return $settings;
1526
}
1527

    
1528
function save_widget_settings($username, $settings, $message = "") {
1529
	global $config, $userindex;
1530
	$user = getUserEntry($username);
1531

    
1532
	if (strlen($message) > 0) {
1533
		$msgout = $message;
1534
	} else {
1535
		$msgout = gettext("Widget configuration has been changed.");
1536
	}
1537

    
1538
	if (isset($user['customsettings'])) {
1539
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1540
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1541
	} else {
1542
		$config['widgets'] = $settings;
1543
		write_config($msgout);
1544
	}
1545
}
1546

    
1547
function auth_get_authserver($name) {
1548
	global $config;
1549

    
1550
	if (is_array($config['system']['authserver'])) {
1551
		foreach ($config['system']['authserver'] as $authcfg) {
1552
			if ($authcfg['name'] == $name) {
1553
				return $authcfg;
1554
			}
1555
		}
1556
	}
1557
	if ($name == "Local Database") {
1558
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1559
	}
1560
}
1561

    
1562
function auth_get_authserver_list() {
1563
	global $config;
1564

    
1565
	$list = array();
1566

    
1567
	if (is_array($config['system']['authserver'])) {
1568
		foreach ($config['system']['authserver'] as $authcfg) {
1569
			/* Add support for disabled entries? */
1570
			$list[$authcfg['name']] = $authcfg;
1571
		}
1572
	}
1573

    
1574
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1575
	return $list;
1576
}
1577

    
1578
function getUserGroups($username, $authcfg, &$attributes = array()) {
1579
	global $config;
1580

    
1581
	$allowed_groups = array();
1582

    
1583
	switch ($authcfg['type']) {
1584
		case 'ldap':
1585
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1586
			break;
1587
		case 'radius':
1588
			$allowed_groups = @radius_get_groups($attributes);
1589
			break;
1590
		default:
1591
			$user = getUserEntry($username);
1592
			$allowed_groups = @local_user_get_groups($user, true);
1593
			break;
1594
	}
1595

    
1596
	$member_groups = array();
1597
	if (is_array($config['system']['group'])) {
1598
		foreach ($config['system']['group'] as $group) {
1599
			if (in_array($group['name'], $allowed_groups)) {
1600
				$member_groups[] = $group['name'];
1601
			}
1602
		}
1603
	}
1604

    
1605
	return $member_groups;
1606
}
1607

    
1608
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1609

    
1610
	if (is_array($username) || is_array($password)) {
1611
		return false;
1612
	}
1613

    
1614
	if (!$authcfg) {
1615
		return local_backed($username, $password);
1616
	}
1617

    
1618
	$authenticated = false;
1619
	switch ($authcfg['type']) {
1620
		case 'ldap':
1621
			if (ldap_backed($username, $password, $authcfg)) {
1622
				$authenticated = true;
1623
			}
1624
			break;
1625
		case 'radius':
1626
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1627
				$authenticated = true;
1628
			}
1629
			break;
1630
		default:
1631
			/* lookup user object by name */
1632
			if (local_backed($username, $password)) {
1633
				$authenticated = true;
1634
			}
1635
			break;
1636
		}
1637

    
1638
	return $authenticated;
1639
}
1640

    
1641
function session_auth() {
1642
	global $config, $_SESSION, $page;
1643

    
1644
	// Handle HTTPS httponly and secure flags
1645
	$currentCookieParams = session_get_cookie_params();
1646
	session_set_cookie_params(
1647
		$currentCookieParams["lifetime"],
1648
		$currentCookieParams["path"],
1649
		NULL,
1650
		($config['system']['webgui']['protocol'] == "https"),
1651
		true
1652
	);
1653

    
1654
	if (!session_id()) {
1655
		session_start();
1656
	}
1657

    
1658
	// Detect protocol change
1659
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1660
		return false;
1661
	}
1662

    
1663
	/* Validate incoming login request */
1664
	$attributes = array();
1665
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1666
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1667
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1668
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1669
			// Generate a new id to avoid session fixation
1670
			session_regenerate_id();
1671
			$_SESSION['Logged_In'] = "True";
1672
			$_SESSION['remoteauth'] = $remoteauth;
1673
			$_SESSION['Username'] = $_POST['usernamefld'];
1674
			$_SESSION['user_radius_attributes'] = $attributes;
1675
			$_SESSION['last_access'] = time();
1676
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1677
			if (!isset($config['system']['webgui']['quietlogin'])) {
1678
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1679
			}
1680
			if (isset($_POST['postafterlogin'])) {
1681
				return true;
1682
			} else {
1683
				if (empty($page)) {
1684
					$page = "/";
1685
				}
1686
				header("Location: {$page}");
1687
			}
1688
			exit;
1689
		} else {
1690
			/* give the user an error message */
1691
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1692
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1693
			if (isAjax()) {
1694
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1695
				return;
1696
			}
1697
		}
1698
	}
1699

    
1700
	/* Show login page if they aren't logged in */
1701
	if (empty($_SESSION['Logged_In'])) {
1702
		return false;
1703
	}
1704

    
1705
	/* If session timeout isn't set, we don't mark sessions stale */
1706
	if (!isset($config['system']['webgui']['session_timeout'])) {
1707
		/* Default to 4 hour timeout if one is not set */
1708
		if ($_SESSION['last_access'] < (time() - 14400)) {
1709
			$_GET['logout'] = true;
1710
			$_SESSION['Logout'] = true;
1711
		} else {
1712
			$_SESSION['last_access'] = time();
1713
		}
1714
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1715
		/* only update if it wasn't ajax */
1716
		if (!isAjax()) {
1717
			$_SESSION['last_access'] = time();
1718
		}
1719
	} else {
1720
		/* Check for stale session */
1721
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1722
			$_GET['logout'] = true;
1723
			$_SESSION['Logout'] = true;
1724
		} else {
1725
			/* only update if it wasn't ajax */
1726
			if (!isAjax()) {
1727
				$_SESSION['last_access'] = time();
1728
			}
1729
		}
1730
	}
1731

    
1732
	/* user hit the logout button */
1733
	if (isset($_GET['logout'])) {
1734

    
1735
		if ($_SESSION['Logout']) {
1736
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1737
		} else {
1738
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1739
		}
1740

    
1741
		/* wipe out $_SESSION */
1742
		$_SESSION = array();
1743

    
1744
		if (isset($_COOKIE[session_name()])) {
1745
			setcookie(session_name(), '', time()-42000, '/');
1746
		}
1747

    
1748
		/* and destroy it */
1749
		session_destroy();
1750

    
1751
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1752
		$scriptElms = count($scriptName);
1753
		$scriptName = $scriptName[$scriptElms-1];
1754

    
1755
		if (isAjax()) {
1756
			return false;
1757
		}
1758

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

    
1762
		return false;
1763
	}
1764

    
1765
	/*
1766
	 * this is for debugging purpose if you do not want to use Ajax
1767
	 * to submit a HTML form. It basically disables the observation
1768
	 * of the submit event and hence does not trigger Ajax.
1769
	 */
1770
	if ($_GET['disable_ajax']) {
1771
		$_SESSION['NO_AJAX'] = "True";
1772
	}
1773

    
1774
	/*
1775
	 * Same to re-enable Ajax.
1776
	 */
1777
	if ($_GET['enable_ajax']) {
1778
		unset($_SESSION['NO_AJAX']);
1779
	}
1780

    
1781
	return true;
1782
}
1783

    
1784
?>
(1-1/51)