Project

General

Profile

Download (61.1 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-2018 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
include_once('phpsessionmanager.inc');
30
if (!$do_not_include_config_gui_inc) {
31
	require_once("config.gui.inc");
32
}
33

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

    
37
/* If this function doesn't exist, we're being called from Captive Portal or
38
   another internal subsystem which does not include authgui.inc */
39
if (function_exists("display_error_form")) {
40
	/* Extra layer of lockout protection. Check if the user is in the GUI
41
	 * lockout table before processing a request */
42

    
43
	/* Fetch the contents of the lockout table. */
44
	exec("/sbin/pfctl -t 'webConfiguratorlockout' -T show", $entries);
45

    
46
	/* If the client is in the lockout table, print an error, kill states, and exit */
47
	if (in_array($_SERVER['REMOTE_ADDR'], array_map('trim', $entries))) {
48
		if (!security_checks_disabled()) {
49
			/* They may never see the error since the connection will be cut off, but try to be nice anyhow. */
50
			display_error_form("501", gettext("Access Denied<br/><br/>Access attempt from a temporarily locked out client address.<br /><br />Try accessing the firewall again after the lockout expires."));
51
			/* If they are locked out, they shouldn't have a state. Disconnect their connections. */
52
			$retval = pfSense_kill_states($_SERVER['REMOTE_ADDR']);
53
			if (is_ipaddrv4($_SERVER['REMOTE_ADDR'])) {
54
				$retval = pfSense_kill_states("0.0.0.0/0", $_SERVER['REMOTE_ADDR']);
55
			} elseif (is_ipaddrv6($_SERVER['REMOTE_ADDR'])) {
56
				$retval = pfSense_kill_states("::", $_SERVER['REMOTE_ADDR']);
57
			}
58
			exit;
59
		}
60
		$security_passed = false;
61
	}
62
}
63

    
64
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
65
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
66
	$found_host = false;
67

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

    
91
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
92
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
93
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
94
				$found_host = true;
95
				break;
96
			}
97
		}
98
	}
99

    
100
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
101
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
102
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
103
				$found_host = true;
104
				break;
105
			}
106
		}
107
	}
108

    
109
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
110
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
111
		foreach ($althosts as $ah) {
112
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
113
				$found_host = true;
114
				break;
115
			}
116
		}
117
	}
118

    
119
	if ($found_host == false) {
120
		if (!security_checks_disabled()) {
121
			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."));
122
			exit;
123
		}
124
		$security_passed = false;
125
	}
126
}
127

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

    
165
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
166
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
167
				foreach ($althosts as $ah) {
168
					if (strcasecmp($referrer_host, $ah) == 0) {
169
						$found_host = true;
170
						break;
171
					}
172
				}
173
			}
174

    
175
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
176
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
177
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
178
						$found_host = true;
179
						break;
180
					}
181
				}
182
			}
183

    
184
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
185
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
186
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
187
						$found_host = true;
188
						break;
189
					}
190
				}
191
			}
192

    
193
			if (!$found_host) {
194
				$interface_list_ips = get_configured_ip_addresses();
195
				foreach ($interface_list_ips as $ilips) {
196
					if (strcasecmp($referrer_host, $ilips) == 0) {
197
						$found_host = true;
198
						break;
199
					}
200
				}
201
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
202
				foreach ($interface_list_ipv6s as $ilipv6s) {
203
					$ilipv6s = explode('%', $ilipv6s)[0];
204
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
205
						$found_host = true;
206
						break;
207
					}
208
				}
209
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
210
					// allow SSH port forwarded connections and links from localhost
211
					$found_host = true;
212
				}
213
			}
214

    
215
			/* Fall back to probing active interface addresses rather than config.xml to allow
216
			 * changed addresses that have not yet been applied.
217
			 * See https://redmine.pfsense.org/issues/8822
218
			 */
219
			if (!$found_host) {
220
				$refifs = get_interface_arr();
221
				foreach ($refifs as $rif) {
222
					if (($referrer_host == find_interface_ip($rif)) ||
223
					    ($referrer_host == find_interface_ipv6($rif)) ||
224
					    ($referrer_host == find_interface_ipv6_ll($rif))) {
225
						$found_host = true;
226
						break;
227
					}
228
				}
229
			}
230
		}
231
		if ($found_host == false) {
232
			if (!security_checks_disabled()) {
233
				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.");
234
				exit;
235
			}
236
			$security_passed = false;
237
		}
238
	} else {
239
		$security_passed = false;
240
	}
241
}
242

    
243
if (function_exists("display_error_form") && $security_passed) {
244
	/* Security checks passed, so it should be OK to turn them back on */
245
	restore_security_checks();
246
}
247
unset($security_passed);
248

    
249
$groupindex = index_groups();
250
$userindex = index_users();
251

    
252
function index_groups() {
253
	global $g, $debug, $config, $groupindex;
254

    
255
	$groupindex = array();
256

    
257
	if (is_array($config['system']['group'])) {
258
		$i = 0;
259
		foreach ($config['system']['group'] as $groupent) {
260
			$groupindex[$groupent['name']] = $i;
261
			$i++;
262
		}
263
	}
264

    
265
	return ($groupindex);
266
}
267

    
268
function index_users() {
269
	global $g, $debug, $config;
270

    
271
	if (is_array($config['system']['user'])) {
272
		$i = 0;
273
		foreach ($config['system']['user'] as $userent) {
274
			$userindex[$userent['name']] = $i;
275
			$i++;
276
		}
277
	}
278

    
279
	return ($userindex);
280
}
281

    
282
function & getUserEntry($name) {
283
	global $debug, $config, $userindex;
284
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
285

    
286
	if (isset($userindex[$name])) {
287
		return $config['system']['user'][$userindex[$name]];
288
	} elseif ($authcfg['type'] != "Local Database") {
289
		$user = array();
290
		$user['name'] = $name;
291
		return $user;
292
	}
293
}
294

    
295
function & getUserEntryByUID($uid) {
296
	global $debug, $config;
297

    
298
	if (is_array($config['system']['user'])) {
299
		foreach ($config['system']['user'] as & $user) {
300
			if ($user['uid'] == $uid) {
301
				return $user;
302
			}
303
		}
304
	}
305

    
306
	return false;
307
}
308

    
309
function & getGroupEntry($name) {
310
	global $debug, $config, $groupindex;
311
	if (isset($groupindex[$name])) {
312
		return $config['system']['group'][$groupindex[$name]];
313
	}
314
}
315

    
316
function & getGroupEntryByGID($gid) {
317
	global $debug, $config;
318

    
319
	if (is_array($config['system']['group'])) {
320
		foreach ($config['system']['group'] as & $group) {
321
			if ($group['gid'] == $gid) {
322
				return $group;
323
			}
324
		}
325
	}
326

    
327
	return false;
328
}
329

    
330
function get_user_privileges(& $user) {
331
	global $config, $_SESSION;
332

    
333
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
334
	$allowed_groups = array();
335

    
336
	$privs = $user['priv'];
337
	if (!is_array($privs)) {
338
		$privs = array();
339
	}
340

    
341
	// cache auth results for a short time to ease load on auth services & logs
342
	if (isset($config['system']['webgui']['auth_refresh_time'])) {
343
		$recheck_time = $config['system']['webgui']['auth_refresh_time'];
344
	} else {
345
		$recheck_time = 30;
346
	}
347

    
348
	if ($authcfg['type'] == "ldap") {
349
		if (isset($_SESSION["ldap_allowed_groups"]) &&
350
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
351
			$allowed_groups = $_SESSION["ldap_allowed_groups"];
352
		} else {
353
			$allowed_groups = @ldap_get_groups($user['name'], $authcfg);
354
			$_SESSION["ldap_allowed_groups"] = $allowed_groups;
355
			$_SESSION["auth_check_time"] = time();
356
		}
357
	} elseif ($authcfg['type'] == "radius") {
358
		if (isset($_SESSION["radius_allowed_groups"]) &&
359
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
360
			$allowed_groups = $_SESSION["radius_allowed_groups"];
361
		} else {
362
			$allowed_groups = @radius_get_groups($_SESSION['user_radius_attributes']);
363
			$_SESSION["radius_allowed_groups"] = $allowed_groups;
364
			$_SESSION["auth_check_time"] = time();
365
		}
366
	}
367

    
368
	if (empty($allowed_groups)) {
369
		$allowed_groups = local_user_get_groups($user, true);
370
	}
371

    
372
	if (is_array($allowed_groups)) {
373
		foreach ($allowed_groups as $name) {
374
			$group = getGroupEntry($name);
375
			if (is_array($group['priv'])) {
376
				$privs = array_merge($privs, $group['priv']);
377
			}
378
		}
379
	}
380

    
381
	return $privs;
382
}
383

    
384
function userHasPrivilege($userent, $privid = false) {
385

    
386
	if (!$privid || !is_array($userent)) {
387
		return false;
388
	}
389

    
390
	$privs = get_user_privileges($userent);
391

    
392
	if (!is_array($privs)) {
393
		return false;
394
	}
395

    
396
	if (!in_array($privid, $privs)) {
397
		return false;
398
	}
399

    
400
	return true;
401
}
402

    
403
function local_backed($username, $passwd) {
404

    
405
	$user = getUserEntry($username);
406
	if (!$user) {
407
		return false;
408
	}
409

    
410
	if (is_account_disabled($username) || is_account_expired($username)) {
411
		return false;
412
	}
413

    
414
	if ($user['bcrypt-hash']) {
415
		if (password_verify($passwd, $user['bcrypt-hash'])) {
416
			return true;
417
		}
418
	}
419

    
420
	//for backwards compatibility
421
	if ($user['password']) {
422
		if (crypt($passwd, $user['password']) == $user['password']) {
423
			return true;
424
		}
425
	}
426

    
427
	if ($user['md5-hash']) {
428
		if (md5($passwd) == $user['md5-hash']) {
429
			return true;
430
		}
431
	}
432

    
433
	return false;
434
}
435

    
436
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
437
	global $config, $debug;
438

    
439
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
440
		/* Nothing to be done here */
441
		return;
442
	}
443

    
444
	foreach($u2del as $user) {
445
		if ($user['uid'] < 2000 || $user['uid'] > 65000) {
446
			continue;
447
		}
448

    
449
		/*
450
		 * If a crontab was created to user, pw userdel will be
451
		 * interactive and can cause issues. Just remove crontab
452
		 * before run it when necessary
453
		 */
454
		unlink_if_exists("/var/cron/tabs/{$user['name']}");
455
		$cmd = "/usr/sbin/pw userdel -n " .
456
		    escapeshellarg($user['name']);
457
		if ($debug) {
458
			log_error(sprintf(gettext("Running: %s"), $cmd));
459
		}
460
		mwexec($cmd);
461
		local_group_del_user($user);
462

    
463
		$system_user = $config['system']['user'];
464
		for ($i = 0; $i < count($system_user); $i++) {
465
			if ($system_user[$i]['name'] == $user['name']) {
466
				log_error("Removing user: {$user['name']}");
467
				unset($config['system']['user'][$i]);
468
				break;
469
			}
470
		}
471
	}
472

    
473
	foreach($g2del as $group) {
474
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
475
			continue;
476
		}
477

    
478
		$cmd = "/usr/sbin/pw groupdel -g " .
479
		    escapeshellarg($group['name']);
480
		if ($debug) {
481
			log_error(sprintf(gettext("Running: %s"), $cmd));
482
		}
483
		mwexec($cmd);
484

    
485
		$system_group = $config['system']['group'];
486
		for ($i = 0; $i < count($system_group); $i++) {
487
			if ($system_group[$i]['name'] == $group['name']) {
488
				log_error("Removing group: {$group['name']}");
489
				unset($config['system']['group'][$i]);
490
				break;
491
			}
492
		}
493
	}
494

    
495
	foreach ($u2add as $user) {
496
		log_error("Adding user: {$user['name']}");
497
		$config['system']['user'][] = $user;
498
	}
499

    
500
	foreach ($g2add as $group) {
501
		log_error("Adding group: {$group['name']}");
502
		$config['system']['group'][] = $group;
503
	}
504

    
505
	/* Sort it alphabetically */
506
	usort($config['system']['user'], function($a, $b) {
507
		return strcmp($a['name'], $b['name']);
508
	});
509
	usort($config['system']['group'], function($a, $b) {
510
		return strcmp($a['name'], $b['name']);
511
	});
512

    
513
	write_config("Sync'd users and groups via XMLRPC");
514

    
515
	/* make sure the all group exists */
516
	$allgrp = getGroupEntryByGID(1998);
517
	local_group_set($allgrp, true);
518

    
519
	foreach ($u2add as $user) {
520
		local_user_set($user);
521
	}
522

    
523
	foreach ($g2add as $group) {
524
		local_group_set($group);
525
	}
526
}
527

    
528
function local_reset_accounts() {
529
	global $debug, $config;
530

    
531
	/* remove local users to avoid uid conflicts */
532
	$fd = popen("/usr/sbin/pw usershow -a", "r");
533
	if ($fd) {
534
		while (!feof($fd)) {
535
			$line = explode(":", fgets($fd));
536
			if ($line[0] != "admin") {
537
				if (!strncmp($line[0], "_", 1)) {
538
					continue;
539
				}
540
				if ($line[2] < 2000) {
541
					continue;
542
				}
543
				if ($line[2] > 65000) {
544
					continue;
545
				}
546
			}
547
			/*
548
			 * If a crontab was created to user, pw userdel will be interactive and
549
			 * can cause issues. Just remove crontab before run it when necessary
550
			 */
551
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
552
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
553
			if ($debug) {
554
				log_error(sprintf(gettext("Running: %s"), $cmd));
555
			}
556
			mwexec($cmd);
557
		}
558
		pclose($fd);
559
	}
560

    
561
	/* remove local groups to avoid gid conflicts */
562
	$gids = array();
563
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
564
	if ($fd) {
565
		while (!feof($fd)) {
566
			$line = explode(":", fgets($fd));
567
			if (!strncmp($line[0], "_", 1)) {
568
				continue;
569
			}
570
			if ($line[2] < 2000) {
571
				continue;
572
			}
573
			if ($line[2] > 65000) {
574
				continue;
575
			}
576
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
577
			if ($debug) {
578
				log_error(sprintf(gettext("Running: %s"), $cmd));
579
			}
580
			mwexec($cmd);
581
		}
582
		pclose($fd);
583
	}
584

    
585
	/* make sure the all group exists */
586
	$allgrp = getGroupEntryByGID(1998);
587
	local_group_set($allgrp, true);
588

    
589
	/* sync all local users */
590
	if (is_array($config['system']['user'])) {
591
		foreach ($config['system']['user'] as $user) {
592
			local_user_set($user);
593
		}
594
	}
595

    
596
	/* sync all local groups */
597
	if (is_array($config['system']['group'])) {
598
		foreach ($config['system']['group'] as $group) {
599
			local_group_set($group);
600
		}
601
	}
602
}
603

    
604
function local_user_set(& $user) {
605
	global $g, $debug;
606

    
607
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
608
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
609
		return;
610
	}
611

    
612

    
613
	$home_base = "/home/";
614
	$user_uid = $user['uid'];
615
	$user_name = $user['name'];
616
	$user_home = "{$home_base}{$user_name}";
617
	$user_shell = "/etc/rc.initial";
618
	$user_group = "nobody";
619

    
620
	// Ensure $home_base exists and is writable
621
	if (!is_dir($home_base)) {
622
		mkdir($home_base, 0755);
623
	}
624

    
625
	$lock_account = false;
626
	/* configure shell type */
627
	/* Cases here should be ordered by most privileged to least privileged. */
628
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
629
		$user_shell = "/bin/tcsh";
630
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
631
		$user_shell = "/usr/local/sbin/scponlyc";
632
	} elseif (userHasPrivilege($user, "user-copy-files")) {
633
		$user_shell = "/usr/local/bin/scponly";
634
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
635
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
636
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
637
		$user_shell = "/sbin/nologin";
638
	} else {
639
		$user_shell = "/sbin/nologin";
640
		$lock_account = true;
641
	}
642

    
643
	/* Lock out disabled or expired users, unless it's root/admin. */
644
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
645
		$user_shell = "/sbin/nologin";
646
		$lock_account = true;
647
	}
648

    
649
	/* root user special handling */
650
	if ($user_uid == 0) {
651
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
652
		if ($debug) {
653
			log_error(sprintf(gettext("Running: %s"), $cmd));
654
		}
655
		$fd = popen($cmd, "w");
656
		if (empty($user['bcrypt-hash'])) {
657
			fwrite($fd, $user['password']);
658
		} else {
659
			fwrite($fd, $user['bcrypt-hash']);
660
		}
661
		pclose($fd);
662
		$user_group = "wheel";
663
		$user_home = "/root";
664
		$user_shell = "/etc/rc.initial";
665
	}
666

    
667
	/* read from pw db */
668
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
669
	$pwread = fgets($fd);
670
	pclose($fd);
671
	$userattrs = explode(":", trim($pwread));
672

    
673
	$skel_dir = '/etc/skel';
674

    
675
	/* determine add or mod */
676
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
677
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
678
	} else {
679
		$user_op = "usermod";
680
	}
681

    
682
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
683
	/* add or mod pw db */
684
	$cmd = "/usr/sbin/pw {$user_op} -q " .
685
			" -u " . escapeshellarg($user_uid) .
686
			" -n " . escapeshellarg($user_name) .
687
			" -g " . escapeshellarg($user_group) .
688
			" -s " . escapeshellarg($user_shell) .
689
			" -d " . escapeshellarg($user_home) .
690
			" -c " . escapeshellarg($comment) .
691
			" -H 0 2>&1";
692

    
693
	if ($debug) {
694
		log_error(sprintf(gettext("Running: %s"), $cmd));
695
	}
696
	$fd = popen($cmd, "w");
697
	if (empty($user['bcrypt-hash'])) {
698
		fwrite($fd, $user['password']);
699
	} else {
700
		fwrite($fd, $user['bcrypt-hash']);
701
	}
702
	pclose($fd);
703

    
704
	/* create user directory if required */
705
	if (!is_dir($user_home)) {
706
		mkdir($user_home, 0700);
707
	}
708
	@chown($user_home, $user_name);
709
	@chgrp($user_home, $user_group);
710

    
711
	/* Make sure all users have last version of config files */
712
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
713
		$target = $user_home . '/' . substr(basename($dot_file), 3);
714
		@copy($dot_file, $target);
715
		@chown($target, $user_name);
716
		@chgrp($target, $user_group);
717
	}
718

    
719
	/* write out ssh authorized key file */
720
	if ($user['authorizedkeys']) {
721
		if (!is_dir("{$user_home}/.ssh")) {
722
			@mkdir("{$user_home}/.ssh", 0700);
723
			@chown("{$user_home}/.ssh", $user_name);
724
		}
725
		$keys = base64_decode($user['authorizedkeys']);
726
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
727
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
728
	} else {
729
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
730
	}
731

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

    
735
}
736

    
737
function local_user_del($user) {
738
	global $debug;
739

    
740
	/* remove all memberships */
741
	local_user_set_groups($user);
742

    
743
	/* Don't remove /root */
744
	if ($user['uid'] != 0) {
745
		$rmhome = "-r";
746
	}
747

    
748
	/* read from pw db */
749
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
750
	$pwread = fgets($fd);
751
	pclose($fd);
752
	$userattrs = explode(":", trim($pwread));
753

    
754
	if ($userattrs[0] != $user['name']) {
755
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
756
		return;
757
	}
758

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

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

    
767
	/* Delete user from groups needs a call to write_config() */
768
	local_group_del_user($user);
769
}
770

    
771
function local_user_set_password(&$user, $password) {
772
	unset($user['password']);
773
	unset($user['md5-hash']);
774
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
775
}
776

    
777
function local_user_get_groups($user, $all = false) {
778
	global $debug, $config;
779

    
780
	$groups = array();
781
	if (!is_array($config['system']['group'])) {
782
		return $groups;
783
	}
784

    
785
	foreach ($config['system']['group'] as $group) {
786
		if ($all || (!$all && ($group['name'] != "all"))) {
787
			if (is_array($group['member'])) {
788
				if (in_array($user['uid'], $group['member'])) {
789
					$groups[] = $group['name'];
790
				}
791
			}
792
		}
793
	}
794

    
795
	if ($all) {
796
		$groups[] = "all";
797
	}
798

    
799
	sort($groups);
800

    
801
	return $groups;
802

    
803
}
804

    
805
function local_user_set_groups($user, $new_groups = NULL) {
806
	global $debug, $config, $groupindex, $userindex;
807

    
808
	if (!is_array($config['system']['group'])) {
809
		return;
810
	}
811

    
812
	$cur_groups = local_user_get_groups($user, true);
813
	$mod_groups = array();
814

    
815
	if (!is_array($new_groups)) {
816
		$new_groups = array();
817
	}
818

    
819
	if (!is_array($cur_groups)) {
820
		$cur_groups = array();
821
	}
822

    
823
	/* determine which memberships to add */
824
	foreach ($new_groups as $groupname) {
825
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
826
			continue;
827
		}
828
		$group = & $config['system']['group'][$groupindex[$groupname]];
829
		$group['member'][] = $user['uid'];
830
		$mod_groups[] = $group;
831

    
832
		/*
833
		 * If it's a new user, make sure it is added before try to
834
		 * add it as a member of a group
835
		 */
836
		if (!isset($userindex[$user['uid']])) {
837
			local_user_set($user);
838
		}
839
	}
840
	unset($group);
841

    
842
	/* determine which memberships to remove */
843
	foreach ($cur_groups as $groupname) {
844
		if (in_array($groupname, $new_groups)) {
845
			continue;
846
		}
847
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
848
			continue;
849
		}
850
		$group = & $config['system']['group'][$groupindex[$groupname]];
851
		if (is_array($group['member'])) {
852
			$index = array_search($user['uid'], $group['member']);
853
			array_splice($group['member'], $index, 1);
854
			$mod_groups[] = $group;
855
		}
856
	}
857
	unset($group);
858

    
859
	/* sync all modified groups */
860
	foreach ($mod_groups as $group) {
861
		local_group_set($group);
862
	}
863
}
864

    
865
function local_group_del_user($user) {
866
	global $config;
867

    
868
	if (!is_array($config['system']['group'])) {
869
		return;
870
	}
871

    
872
	foreach ($config['system']['group'] as $group) {
873
		if (is_array($group['member'])) {
874
			foreach ($group['member'] as $idx => $uid) {
875
				if ($user['uid'] == $uid) {
876
					unset($config['system']['group']['member'][$idx]);
877
				}
878
			}
879
		}
880
	}
881
}
882

    
883
function local_group_set($group, $reset = false) {
884
	global $debug;
885

    
886
	$group_name = $group['name'];
887
	$group_gid = $group['gid'];
888
	$group_members = '';
889

    
890
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
891
		$group_members = implode(",", $group['member']);
892
	}
893

    
894
	if (empty($group_name)) {
895
		return;
896
	}
897

    
898
	// If the group is now remote, make sure there is no local group with the same name
899
	if ($group['scope'] == "remote") {
900
		local_group_del($group);
901
		return;
902
	}
903

    
904
	/* determine add or mod */
905
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
906
		$group_op = "groupmod -l";
907
	} else {
908
		$group_op = "groupadd -n";
909
	}
910

    
911
	/* add or mod group db */
912
	$cmd = "/usr/sbin/pw {$group_op} " .
913
		escapeshellarg($group_name) .
914
		" -g " . escapeshellarg($group_gid) .
915
		" -M " . escapeshellarg($group_members) . " 2>&1";
916

    
917
	if ($debug) {
918
		log_error(sprintf(gettext("Running: %s"), $cmd));
919
	}
920

    
921
	mwexec($cmd);
922
}
923

    
924
function local_group_del($group) {
925
	global $debug;
926

    
927
	/* delete from group db */
928
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
929

    
930
	if ($debug) {
931
		log_error(sprintf(gettext("Running: %s"), $cmd));
932
	}
933
	mwexec($cmd);
934
}
935

    
936
function ldap_test_connection($authcfg) {
937
	if ($authcfg) {
938
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
939
			$ldapproto = "ldaps";
940
		} else {
941
			$ldapproto = "ldap";
942
		}
943
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
944
		$ldapport = $authcfg['ldap_port'];
945
		if (!empty($ldapport)) {
946
			$ldapserver .= ":{$ldapport}";
947
		}
948
	} else {
949
		return false;
950
	}
951

    
952
	/* first check if there is even an LDAP server populated */
953
	if (!$ldapserver) {
954
		return false;
955
	}
956

    
957
	/* Setup CA environment if needed. */
958
	ldap_setup_caenv($authcfg);
959

    
960
	/* connect and see if server is up */
961
	$error = false;
962
	if (!($ldap = ldap_connect($ldapserver))) {
963
		$error = true;
964
	}
965

    
966
	if ($error == true) {
967
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
968
		return false;
969
	}
970

    
971
	return true;
972
}
973

    
974
function ldap_setup_caenv($authcfg) {
975
	global $g;
976
	require_once("certs.inc");
977

    
978
	unset($caref);
979
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
980
		putenv('LDAPTLS_REQCERT=never');
981
		return;
982
	} elseif ($authcfg['ldap_caref'] == "global") {
983
		putenv('LDAPTLS_REQCERT=hard');
984
		putenv("LDAPTLS_CACERTDIR=/etc/ssl/");
985
		putenv("LDAPTLS_CACERT=/etc/ssl/cert.pem");
986
	} else {
987
		$caref = lookup_ca($authcfg['ldap_caref']);
988
		$param = array('caref' => $authcfg['ldap_caref']);
989
		$cachain = ca_chain($param);
990
		if (!$caref) {
991
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
992
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
993
			putenv('LDAPTLS_REQCERT=hard');
994
			return;
995
		}
996
		if (!is_dir("{$g['varrun_path']}/certs")) {
997
			@mkdir("{$g['varrun_path']}/certs");
998
		}
999
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
1000
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
1001
		}
1002
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", $cachain);
1003
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
1004
		putenv('LDAPTLS_REQCERT=hard');
1005
		/* XXX: Probably even the hashed link should be created for this? */
1006
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
1007
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
1008
	}
1009
}
1010

    
1011
function ldap_test_bind($authcfg) {
1012
	global $debug, $config, $g;
1013

    
1014
	if ($authcfg) {
1015
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1016
			$ldapproto = "ldaps";
1017
		} else {
1018
			$ldapproto = "ldap";
1019
		}
1020
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1021
		$ldapport = $authcfg['ldap_port'];
1022
		if (!empty($ldapport)) {
1023
			$ldapserver .= ":{$ldapport}";
1024
		}
1025
		$ldapbasedn = $authcfg['ldap_basedn'];
1026
		$ldapbindun = $authcfg['ldap_binddn'];
1027
		$ldapbindpw = $authcfg['ldap_bindpw'];
1028
		$ldapver = $authcfg['ldap_protver'];
1029
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1030
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1031
			$ldapanon = true;
1032
		} else {
1033
			$ldapanon = false;
1034
		}
1035
	} else {
1036
		return false;
1037
	}
1038

    
1039
	/* first check if there is even an LDAP server populated */
1040
	if (!$ldapserver) {
1041
		return false;
1042
	}
1043

    
1044
	/* Setup CA environment if needed. */
1045
	ldap_setup_caenv($authcfg);
1046

    
1047
	/* connect and see if server is up */
1048
	$error = false;
1049
	if (!($ldap = ldap_connect($ldapserver))) {
1050
		$error = true;
1051
	}
1052

    
1053
	if ($error == true) {
1054
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1055
		return false;
1056
	}
1057

    
1058
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1059
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1060
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1061
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1062
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1063

    
1064
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1065
		if (!(@ldap_start_tls($ldap))) {
1066
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1067
			@ldap_close($ldap);
1068
			return false;
1069
		}
1070
	}
1071

    
1072
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1073
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1074
	if ($ldapanon == true) {
1075
		if (!($res = @ldap_bind($ldap))) {
1076
			@ldap_close($ldap);
1077
			return false;
1078
		}
1079
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1080
		@ldap_close($ldap);
1081
		return false;
1082
	}
1083

    
1084
	@ldap_unbind($ldap);
1085

    
1086
	return true;
1087
}
1088

    
1089
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1090
	global $debug, $config, $g;
1091

    
1092
	if (!function_exists("ldap_connect")) {
1093
		return;
1094
	}
1095

    
1096
	$ous = array();
1097

    
1098
	if ($authcfg) {
1099
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1100
			$ldapproto = "ldaps";
1101
		} else {
1102
			$ldapproto = "ldap";
1103
		}
1104
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1105
		$ldapport = $authcfg['ldap_port'];
1106
		if (!empty($ldapport)) {
1107
			$ldapserver .= ":{$ldapport}";
1108
		}
1109
		$ldapbasedn = $authcfg['ldap_basedn'];
1110
		$ldapbindun = $authcfg['ldap_binddn'];
1111
		$ldapbindpw = $authcfg['ldap_bindpw'];
1112
		$ldapver = $authcfg['ldap_protver'];
1113
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1114
			$ldapanon = true;
1115
		} else {
1116
			$ldapanon = false;
1117
		}
1118
		$ldapname = $authcfg['name'];
1119
		$ldapfallback = false;
1120
		$ldapscope = $authcfg['ldap_scope'];
1121
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1122
	} else {
1123
		return false;
1124
	}
1125

    
1126
	/* first check if there is even an LDAP server populated */
1127
	if (!$ldapserver) {
1128
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1129
		return $ous;
1130
	}
1131

    
1132
	/* Setup CA environment if needed. */
1133
	ldap_setup_caenv($authcfg);
1134

    
1135
	/* connect and see if server is up */
1136
	$error = false;
1137
	if (!($ldap = ldap_connect($ldapserver))) {
1138
		$error = true;
1139
	}
1140

    
1141
	if ($error == true) {
1142
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1143
		return $ous;
1144
	}
1145

    
1146
	$ldapfilter = "(|(ou=*)(cn=Users))";
1147

    
1148
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1149
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1150
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1151
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1152
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1153

    
1154
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1155
		if (!(@ldap_start_tls($ldap))) {
1156
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1157
			@ldap_close($ldap);
1158
			return false;
1159
		}
1160
	}
1161

    
1162
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1163
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1164
	if ($ldapanon == true) {
1165
		if (!($res = @ldap_bind($ldap))) {
1166
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1167
			@ldap_close($ldap);
1168
			return $ous;
1169
		}
1170
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1171
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1172
		@ldap_close($ldap);
1173
		return $ous;
1174
	}
1175

    
1176
	if ($ldapscope == "one") {
1177
		$ldapfunc = "ldap_list";
1178
	} else {
1179
		$ldapfunc = "ldap_search";
1180
	}
1181

    
1182
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1183
	$info = @ldap_get_entries($ldap, $search);
1184

    
1185
	if (is_array($info)) {
1186
		foreach ($info as $inf) {
1187
			if (!$show_complete_ou) {
1188
				$inf_split = explode(",", $inf['dn']);
1189
				$ou = $inf_split[0];
1190
				$ou = str_replace("OU=", "", $ou);
1191
				$ou = str_replace("CN=", "", $ou);
1192
			} else {
1193
				if ($inf['dn']) {
1194
					$ou = $inf['dn'];
1195
				}
1196
			}
1197
			if ($ou) {
1198
				$ous[] = $ou;
1199
			}
1200
		}
1201
	}
1202

    
1203
	@ldap_unbind($ldap);
1204

    
1205
	return $ous;
1206
}
1207

    
1208
function ldap_get_groups($username, $authcfg) {
1209
	global $debug, $config;
1210

    
1211
	if (!function_exists("ldap_connect")) {
1212
		return;
1213
	}
1214

    
1215
	if (!$username) {
1216
		return false;
1217
	}
1218

    
1219
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1220
		$username_split = explode("@", $username);
1221
		$username = $username_split[0];
1222
	}
1223

    
1224
	if (stristr($username, "\\")) {
1225
		$username_split = explode("\\", $username);
1226
		$username = $username_split[0];
1227
	}
1228

    
1229
	//log_error("Getting LDAP groups for {$username}.");
1230
	if ($authcfg) {
1231
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1232
			$ldapproto = "ldaps";
1233
		} else {
1234
			$ldapproto = "ldap";
1235
		}
1236
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1237
		$ldapport = $authcfg['ldap_port'];
1238
		if (!empty($ldapport)) {
1239
			$ldapserver .= ":{$ldapport}";
1240
		}
1241
		$ldapbasedn = $authcfg['ldap_basedn'];
1242
		$ldapbindun = $authcfg['ldap_binddn'];
1243
		$ldapbindpw = $authcfg['ldap_bindpw'];
1244
		$ldapauthcont = $authcfg['ldap_authcn'];
1245
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1246
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1247
		if (isset($authcfg['ldap_rfc2307'])) {
1248
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1249
		} else {
1250
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1251
		}
1252
		$ldaptype = "";
1253
		$ldapver = $authcfg['ldap_protver'];
1254
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1255
			$ldapanon = true;
1256
		} else {
1257
			$ldapanon = false;
1258
		}
1259
		$ldapname = $authcfg['name'];
1260
		$ldapfallback = false;
1261
		$ldapscope = $authcfg['ldap_scope'];
1262
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1263
	} else {
1264
		return false;
1265
	}
1266

    
1267
	if (isset($authcfg['ldap_rfc2307'])) {
1268
		$ldapdn = $ldapbasedn;
1269
	} else {
1270
		$ldapdn = $_SESSION['ldapdn'];
1271
	}
1272

    
1273
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1274
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1275
	$memberof = array();
1276

    
1277
	/* Setup CA environment if needed. */
1278
	ldap_setup_caenv($authcfg);
1279

    
1280
	/* connect and see if server is up */
1281
	$error = false;
1282
	if (!($ldap = ldap_connect($ldapserver))) {
1283
		$error = true;
1284
	}
1285

    
1286
	if ($error == true) {
1287
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1288
		return $memberof;
1289
	}
1290

    
1291
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1292
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1293
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1294
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1295
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1296

    
1297
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1298
		if (!(@ldap_start_tls($ldap))) {
1299
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1300
			@ldap_close($ldap);
1301
			return false;
1302
		}
1303
	}
1304

    
1305
	/* bind as user that has rights to read group attributes */
1306
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1307
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1308
	if ($ldapanon == true) {
1309
		if (!($res = @ldap_bind($ldap))) {
1310
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1311
			@ldap_close($ldap);
1312
			return false;
1313
		}
1314
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1315
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1316
		@ldap_close($ldap);
1317
		return $memberof;
1318
	}
1319

    
1320
	/* get groups from DN found */
1321
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1322
	/* since we know the DN is in $_SESSION['ldapdn'] */
1323
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1324
	if ($ldapscope == "one") {
1325
		$ldapfunc = "ldap_list";
1326
	} else {
1327
		$ldapfunc = "ldap_search";
1328
	}
1329

    
1330
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1331
	$info = @ldap_get_entries($ldap, $search);
1332

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

    
1335
	if (is_array($gresults)) {
1336
		/* Iterate through the groups and throw them into an array */
1337
		foreach ($gresults as $grp) {
1338
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1339
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1340
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1341
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1342
			}
1343
		}
1344
	}
1345

    
1346
	/* Time to close LDAP connection */
1347
	@ldap_unbind($ldap);
1348

    
1349
	$groups = print_r($memberof, true);
1350

    
1351
	//log_error("Returning groups ".$groups." for user $username");
1352

    
1353
	return $memberof;
1354
}
1355

    
1356
function ldap_format_host($host) {
1357
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1358
}
1359

    
1360
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1361
	global $debug, $config;
1362

    
1363
	if (!$username) {
1364
		$attributes['error_message'] = gettext("Invalid Login.");
1365
		return false;
1366
	}
1367

    
1368
	if (!function_exists("ldap_connect")) {
1369
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1370
		$attributes['error_message'] = gettext("Internal error during authentication.");
1371
		return null;
1372
	}
1373

    
1374
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1375
		$username_split = explode("@", $username);
1376
		$username = $username_split[0];
1377
	}
1378
	if (stristr($username, "\\")) {
1379
		$username_split = explode("\\", $username);
1380
		$username = $username_split[0];
1381
	}
1382

    
1383
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1384

    
1385
	if ($authcfg) {
1386
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1387
			$ldapproto = "ldaps";
1388
		} else {
1389
			$ldapproto = "ldap";
1390
		}
1391
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1392
		$ldapport = $authcfg['ldap_port'];
1393
		if (!empty($ldapport)) {
1394
			$ldapserver .= ":{$ldapport}";
1395
		}
1396
		$ldapbasedn = $authcfg['ldap_basedn'];
1397
		$ldapbindun = $authcfg['ldap_binddn'];
1398
		$ldapbindpw = $authcfg['ldap_bindpw'];
1399
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1400
			$ldapanon = true;
1401
		} else {
1402
			$ldapanon = false;
1403
		}
1404
		$ldapauthcont = $authcfg['ldap_authcn'];
1405
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1406
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1407
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1408
		$ldapfilter = "";
1409
		if (!$ldapextendedqueryenabled) {
1410
			$ldapfilter = "({$ldapnameattribute}={$username})";
1411
		} else {
1412
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1413
		}
1414
		$ldaptype = "";
1415
		$ldapver = $authcfg['ldap_protver'];
1416
		$ldapname = $authcfg['name'];
1417
		$ldapscope = $authcfg['ldap_scope'];
1418
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1419
	} else {
1420
		return null;
1421
	}
1422

    
1423
	/* first check if there is even an LDAP server populated */
1424
	if (!$ldapserver) {
1425
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1426
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1427
		return null;
1428
	}
1429

    
1430
	/* Setup CA environment if needed. */
1431
	ldap_setup_caenv($authcfg);
1432

    
1433
	/* Make sure we can connect to LDAP */
1434
	$error = false;
1435
	if (!($ldap = ldap_connect($ldapserver))) {
1436
		$error = true;
1437
	}
1438

    
1439
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1440
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1441
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1442
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1443
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1444

    
1445
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1446
		if (!(@ldap_start_tls($ldap))) {
1447
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1448
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1449
			@ldap_close($ldap);
1450
			return null;
1451
		}
1452
	}
1453

    
1454
	if ($error == true) {
1455
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1456
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1457
		return null;
1458
	}
1459

    
1460
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1461
	$error = false;
1462
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1463
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1464
	if ($ldapanon == true) {
1465
		if (!($res = @ldap_bind($ldap))) {
1466
			$error = true;
1467
		}
1468
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1469
		$error = true;
1470
	}
1471

    
1472
	if ($error == true) {
1473
		@ldap_close($ldap);
1474
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1475
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1476
		return null;
1477
	}
1478

    
1479
	/* Get LDAP Authcontainers and split em up. */
1480
	$ldac_splits = explode(";", $ldapauthcont);
1481

    
1482
	/* setup the usercount so we think we haven't found anyone yet */
1483
	$usercount = 0;
1484

    
1485
	/*****************************************************************/
1486
	/*  We first find the user based on username and filter          */
1487
	/*  then, once we find the first occurrence of that person       */
1488
	/*  we set session variables to point to the OU and DN of the    */
1489
	/*  person.  To later be used by ldap_get_groups.                */
1490
	/*  that way we don't have to search twice.                      */
1491
	/*****************************************************************/
1492
	if ($debug) {
1493
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1494
	}
1495
	/* Iterate through the user containers for search */
1496
	foreach ($ldac_splits as $i => $ldac_split) {
1497
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1498
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1499
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1500
		/* Make sure we just use the first user we find */
1501
		if ($debug) {
1502
			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)));
1503
		}
1504
		if ($ldapscope == "one") {
1505
			$ldapfunc = "ldap_list";
1506
		} else {
1507
			$ldapfunc = "ldap_search";
1508
		}
1509
		/* Support legacy auth container specification. */
1510
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1511
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1512
		} else {
1513
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1514
		}
1515
		if (!$search) {
1516
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1517
			continue;
1518
		}
1519
		$info = ldap_get_entries($ldap, $search);
1520
		$matches = $info['count'];
1521
		if ($matches == 1) {
1522
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1523
			$_SESSION['ldapou'] = $ldac_split[$i];
1524
			$_SESSION['ldapon'] = "true";
1525
			$usercount = 1;
1526
			break;
1527
		}
1528
	}
1529

    
1530
	if ($usercount != 1) {
1531
		@ldap_unbind($ldap);
1532
		if ($debug) {
1533
			if ($usercount === 0) {
1534
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1535
			} else {
1536
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1537
			}
1538
		}
1539
		$attributes['error_message'] = gettext("Invalid login specified.");
1540
		return false;
1541
	}
1542

    
1543
	/* Now lets bind as the user we found */
1544
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1545
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1546
		if ($debug) {
1547
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1548
		}
1549
		@ldap_unbind($ldap);
1550
		return false;
1551
	}
1552

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

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

    
1561
	return true;
1562
}
1563

    
1564
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1565
	global $debug, $config;
1566
	$ret = false;
1567

    
1568
	require_once("Auth/RADIUS.php");
1569
	require_once("Crypt/CHAP.php");
1570

    
1571
	if ($authcfg) {
1572
		$radiusservers = array();
1573
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1574
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1575
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1576
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1577
		if(isset($authcfg['radius_protocol'])) {
1578
			$radius_protocol = $authcfg['radius_protocol'];
1579
		} else {
1580
			$radius_protocol = 'PAP';
1581
		}
1582
	} else {
1583
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1584
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1585
		return null;
1586
	}
1587

    
1588
	// Create our instance
1589
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1590
	$rauth = new $classname($username, $password);
1591

    
1592
	/* Add new servers to our instance */
1593
	foreach ($radiusservers as $radsrv) {
1594
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1595
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1596
	}
1597

    
1598
	// Construct data package
1599
	$rauth->username = $username;
1600
	switch ($radius_protocol) {
1601
		case 'CHAP_MD5':
1602
		case 'MSCHAPv1':
1603
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1604
			$crpt = new $classname;
1605
			$crpt->username = $username;
1606
			$crpt->password = $password;
1607
			$rauth->challenge = $crpt->challenge;
1608
			$rauth->chapid = $crpt->chapid;
1609
			$rauth->response = $crpt->challengeResponse();
1610
			$rauth->flags = 1;
1611
			break;
1612

    
1613
		case 'MSCHAPv2':
1614
			$crpt = new Crypt_CHAP_MSv2;
1615
			$crpt->username = $username;
1616
			$crpt->password = $password;
1617
			$rauth->challenge = $crpt->authChallenge;
1618
			$rauth->peerChallenge = $crpt->peerChallenge;
1619
			$rauth->chapid = $crpt->chapid;
1620
			$rauth->response = $crpt->challengeResponse();
1621
			break;
1622

    
1623
		default:
1624
			$rauth->password = $password;
1625
			break;
1626
	}
1627

    
1628
	if (PEAR::isError($rauth->start())) {
1629
		$ret = null;
1630
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1631
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1632
	} else {
1633
		$nasid = $attributes['nas_identifier'];
1634
		$nasip = $authcfg['radius_nasip_attribute'];
1635
		if (empty($nasid)) {
1636
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1637
		}
1638
		if (!is_ipaddr($nasip)) {
1639
			$nasip = get_interface_ip($nasip);
1640
			
1641
			if (!is_ipaddr($nasip)) {
1642
				$nasip = get_interface_ip();//We use wan interface IP as fallback for NAS-IP-Address
1643
			}
1644
		}
1645
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1646

    
1647
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1648
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1649
		
1650
		if(!empty($attributes['calling_station_id'])) {
1651
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1652
		}
1653
		// Carefully check that interface has a MAC address
1654
		if(!empty($nasmac)) {
1655
			$nasmac = mac_format($nasmac);
1656
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1657
		}
1658
		if(!empty($attributes['nas_port_type'])) {
1659
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1660
		}		
1661
		if(!empty($attributes['nas_port'])) {
1662
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1663
		}
1664
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1665
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1666
		}
1667
	}
1668

    
1669
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1670

    
1671
	/* Send request */
1672
	$result = $rauth->send();
1673
	if (PEAR::isError($result)) {
1674
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1675
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1676
		$ret = null;
1677
	} else if ($result === true) {
1678
		$ret = true;
1679
	} else {
1680
		$ret = false;
1681
	}
1682

    
1683
	
1684
	// Get attributes, even if auth failed.
1685
	if ($rauth->getAttributes()) {
1686
	$attributes = array_merge($attributes,$rauth->listAttributes());
1687

    
1688
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1689
	if (!empty($attributes['session_terminate_time'])) {
1690
			$stt = &$attributes['session_terminate_time'];
1691
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1692
		}
1693
	}
1694
	
1695
	// close OO RADIUS_AUTHENTICATION
1696
	$rauth->close();
1697

    
1698
	return $ret;
1699
}
1700

    
1701
/*
1702
	$attributes must contain a "class" key containing the groups and local
1703
	groups must exist to match.
1704
*/
1705
function radius_get_groups($attributes) {
1706
	$groups = array();
1707
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1708
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1709
		$groups = array();
1710
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1711
			foreach ($attributes['class'] as $class) {
1712
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1713
			}
1714
		}
1715

    
1716
		foreach ($groups as & $grp) {
1717
			$grp = trim($grp);
1718
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1719
				$grp = substr($grp, 3);
1720
			}
1721
		}
1722
	}
1723
	return $groups;
1724
}
1725

    
1726
function get_user_expiration_date($username) {
1727
	$user = getUserEntry($username);
1728
	if ($user['expires']) {
1729
		return $user['expires'];
1730
	}
1731
}
1732

    
1733
function is_account_expired($username) {
1734
	$expirydate = get_user_expiration_date($username);
1735
	if ($expirydate) {
1736
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1737
			return true;
1738
		}
1739
	}
1740

    
1741
	return false;
1742
}
1743

    
1744
function is_account_disabled($username) {
1745
	$user = getUserEntry($username);
1746
	if (isset($user['disabled'])) {
1747
		return true;
1748
	}
1749

    
1750
	return false;
1751
}
1752

    
1753
function get_user_settings($username) {
1754
	global $config;
1755
	$settings = array();
1756
	$settings['widgets'] = $config['widgets'];
1757
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1758
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1759
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1760
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1761
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1762
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1763
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1764
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1765
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1766
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1767
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1768
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1769
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1770
	$user = getUserEntry($username);
1771
	if (isset($user['customsettings'])) {
1772
		$settings['customsettings'] = true;
1773
		if (isset($user['widgets'])) {
1774
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1775
			$settings['widgets'] = $user['widgets'];
1776
		}
1777
		if (isset($user['dashboardcolumns'])) {
1778
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1779
		}
1780
		if (isset($user['webguicss'])) {
1781
			$settings['webgui']['webguicss'] = $user['webguicss'];
1782
		}
1783
		if (isset($user['webguihostnamemenu'])) {
1784
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1785
		}
1786
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1787
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1788
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1789
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1790
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1791
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1792
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1793
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1794
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1795
	} else {
1796
		$settings['customsettings'] = false;
1797
	}
1798

    
1799
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1800
		$settings['webgui']['dashboardcolumns'] = 2;
1801
	}
1802

    
1803
	return $settings;
1804
}
1805

    
1806
function save_widget_settings($username, $settings, $message = "") {
1807
	global $config, $userindex;
1808
	$user = getUserEntry($username);
1809

    
1810
	if (strlen($message) > 0) {
1811
		$msgout = $message;
1812
	} else {
1813
		$msgout = gettext("Widget configuration has been changed.");
1814
	}
1815

    
1816
	if (isset($user['customsettings'])) {
1817
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1818
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1819
	} else {
1820
		$config['widgets'] = $settings;
1821
		write_config($msgout);
1822
	}
1823
}
1824

    
1825
function auth_get_authserver($name) {
1826
	global $config;
1827

    
1828
	if (is_array($config['system']['authserver'])) {
1829
		foreach ($config['system']['authserver'] as $authcfg) {
1830
			if ($authcfg['name'] == $name) {
1831
				return $authcfg;
1832
			}
1833
		}
1834
	}
1835
	if ($name == "Local Database") {
1836
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1837
	}
1838
}
1839

    
1840
function auth_get_authserver_list() {
1841
	global $config;
1842

    
1843
	$list = array();
1844

    
1845
	if (is_array($config['system']['authserver'])) {
1846
		foreach ($config['system']['authserver'] as $authcfg) {
1847
			/* Add support for disabled entries? */
1848
			$list[$authcfg['name']] = $authcfg;
1849
		}
1850
	}
1851

    
1852
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1853
	return $list;
1854
}
1855

    
1856
function getUserGroups($username, $authcfg, &$attributes = array()) {
1857
	global $config;
1858

    
1859
	$allowed_groups = array();
1860

    
1861
	switch ($authcfg['type']) {
1862
		case 'ldap':
1863
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1864
			break;
1865
		case 'radius':
1866
			$allowed_groups = @radius_get_groups($attributes);
1867
			break;
1868
		default:
1869
			$user = getUserEntry($username);
1870
			$allowed_groups = @local_user_get_groups($user, true);
1871
			break;
1872
	}
1873

    
1874
	$member_groups = array();
1875
	if (is_array($config['system']['group'])) {
1876
		foreach ($config['system']['group'] as $group) {
1877
			if (in_array($group['name'], $allowed_groups)) {
1878
				$member_groups[] = $group['name'];
1879
			}
1880
		}
1881
	}
1882

    
1883
	return $member_groups;
1884
}
1885

    
1886
/*
1887
Possible return values : 
1888
true : authentication worked
1889
false : authentication failed (invalid login/password, not enought permission, etc...)
1890
null : error during authentication process (unable to reach remote server, etc...)
1891
*/
1892
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1893

    
1894
	if (is_array($username) || is_array($password)) {
1895
		return false;
1896
	}
1897

    
1898
	if (!$authcfg) {
1899
		return local_backed($username, $password, $attributes);
1900
	}
1901

    
1902
	$authenticated = false;
1903
	switch ($authcfg['type']) {
1904
		case 'ldap':
1905
			$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1906
			break;
1907
		case 'radius':
1908
			$authenticated = radius_backed($username, $password, $authcfg, $attributes);
1909
			break;
1910
		default:
1911
			/* lookup user object by name */
1912
			$authenticated = local_backed($username, $password, $attributes);
1913
			break;
1914
		}
1915

    
1916
	return $authenticated;
1917
}
1918

    
1919
function session_auth() {
1920
	global $config, $_SESSION, $page;
1921

    
1922
	// Handle HTTPS httponly and secure flags
1923
	$currentCookieParams = session_get_cookie_params();
1924
	session_set_cookie_params(
1925
		$currentCookieParams["lifetime"],
1926
		$currentCookieParams["path"],
1927
		NULL,
1928
		($config['system']['webgui']['protocol'] == "https"),
1929
		true
1930
	);
1931

    
1932
	phpsession_begin();
1933

    
1934
	// Detect protocol change
1935
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1936
		phpsession_end();
1937
		return false;
1938
	}
1939

    
1940
	/* Validate incoming login request */
1941
	$attributes = array();
1942
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1943
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1944
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
1945
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1946
			// Generate a new id to avoid session fixation
1947
			session_regenerate_id();
1948
			$_SESSION['Logged_In'] = "True";
1949
			$_SESSION['remoteauth'] = $remoteauth;
1950
			if ($remoteauth) {
1951
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
1952
					$_SESSION['authsource'] = gettext("Local Database");
1953
				} else {
1954
					$_SESSION['authsource'] = strtoupper(gettext($authcfg['type'])) . "/{$authcfg['name']}";
1955
				}
1956
			} else {
1957
				$_SESSION['authsource'] = gettext('Local Database Fallback') ;
1958
			}
1959
			$_SESSION['Username'] = $_POST['usernamefld'];
1960
			$_SESSION['user_radius_attributes'] = $attributes;
1961
			$_SESSION['last_access'] = time();
1962
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1963
			phpsession_end(true);
1964
			if (!isset($config['system']['webgui']['quietlogin'])) {
1965
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
1966
			}
1967
			if (isset($_POST['postafterlogin'])) {
1968
				return true;
1969
			} else {
1970
				if (empty($page)) {
1971
					$page = "/";
1972
				}
1973
				header("Location: {$page}");
1974
			}
1975
			exit;
1976
		} else {
1977
			/* give the user an error message */
1978
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
1979
			log_auth(sprintf(gettext("webConfigurator authentication error for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
1980
			if (isAjax()) {
1981
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1982
				return;
1983
			}
1984
		}
1985
	}
1986

    
1987
	/* Show login page if they aren't logged in */
1988
	if (empty($_SESSION['Logged_In'])) {
1989
		phpsession_end(true);
1990
		return false;
1991
	}
1992

    
1993
	/* If session timeout isn't set, we don't mark sessions stale */
1994
	if (!isset($config['system']['webgui']['session_timeout'])) {
1995
		/* Default to 4 hour timeout if one is not set */
1996
		if ($_SESSION['last_access'] < (time() - 14400)) {
1997
			$_POST['logout'] = true;
1998
			$_SESSION['Logout'] = true;
1999
		} else {
2000
			$_SESSION['last_access'] = time();
2001
		}
2002
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2003
		/* only update if it wasn't ajax */
2004
		if (!isAjax()) {
2005
			$_SESSION['last_access'] = time();
2006
		}
2007
	} else {
2008
		/* Check for stale session */
2009
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2010
			$_POST['logout'] = true;
2011
			$_SESSION['Logout'] = true;
2012
		} else {
2013
			/* only update if it wasn't ajax */
2014
			if (!isAjax()) {
2015
				$_SESSION['last_access'] = time();
2016
			}
2017
		}
2018
	}
2019

    
2020
	/* user hit the logout button */
2021
	if (isset($_POST['logout'])) {
2022

    
2023
		if ($_SESSION['Logout']) {
2024
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2025
		} else {
2026
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2027
		}
2028

    
2029
		/* wipe out $_SESSION */
2030
		$_SESSION = array();
2031

    
2032
		if (isset($_COOKIE[session_name()])) {
2033
			setcookie(session_name(), '', time()-42000, '/');
2034
		}
2035

    
2036
		/* and destroy it */
2037
		phpsession_destroy();
2038

    
2039
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2040
		$scriptElms = count($scriptName);
2041
		$scriptName = $scriptName[$scriptElms-1];
2042

    
2043
		if (isAjax()) {
2044
			return false;
2045
		}
2046

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

    
2050
		return false;
2051
	}
2052

    
2053
	/*
2054
	 * this is for debugging purpose if you do not want to use Ajax
2055
	 * to submit a HTML form. It basically disables the observation
2056
	 * of the submit event and hence does not trigger Ajax.
2057
	 */
2058
	if ($_REQUEST['disable_ajax']) {
2059
		$_SESSION['NO_AJAX'] = "True";
2060
	}
2061

    
2062
	/*
2063
	 * Same to re-enable Ajax.
2064
	 */
2065
	if ($_REQUEST['enable_ajax']) {
2066
		unset($_SESSION['NO_AJAX']);
2067
	}
2068
	phpsession_end(true);
2069
	return true;
2070
}
2071

    
2072
function print_credit() {
2073
	global $g;
2074

    
2075
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_name"] . '</a>' .
2076
			gettext(' is developed and maintained by ') .
2077
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2078
			'<a target="_blank" href="https://pfsense.org/license">' .
2079
			gettext(' View license.') . '</a>';
2080
}
2081
function get_user_remote_address() {
2082
	$remote_address = $_SERVER['REMOTE_ADDR'];
2083
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2084
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2085
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2086
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2087
	}
2088
	return $remote_address;
2089
}
2090
function get_user_remote_authsource() {
2091
	$authsource = "";
2092
	if (!empty($_SESSION['authsource'])) {
2093
		$authsource .= " ({$_SESSION['authsource']})";
2094
	}
2095
	return $authsource;
2096
}
2097
?>
(2-2/60)