Project

General

Profile

Download (72.3 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-2013 BSD Perimeter
10
 * Copyright (c) 2013-2016 Electric Sheep Fencing
11
 * Copyright (c) 2014-2022 Rubicon Communications, LLC (Netgate)
12
 * All rights reserved.
13
 *
14
 * Licensed under the Apache License, Version 2.0 (the "License");
15
 * you may not use this file except in compliance with the License.
16
 * You may obtain a copy of the License at
17
 *
18
 * http://www.apache.org/licenses/LICENSE-2.0
19
 *
20
 * Unless required by applicable law or agreed to in writing, software
21
 * distributed under the License is distributed on an "AS IS" BASIS,
22
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
 * See the License for the specific language governing permissions and
24
 * limitations under the License.
25
 */
26

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

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

    
39
/* Possible user password hash types.
40
 * See https://redmine.pfsense.org/issues/12855
41
 */
42
global $auth_password_hash_types;
43
$auth_password_hash_types = array(
44
	'bcrypt' => gettext('bcrypt -- Blowfish-based crypt'),
45
	'sha512' => gettext('SHA-512 -- SHA-512-based crypt')
46
);
47

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

    
54
	/* Fetch the contents of the lockout table. */
55
	$entries = array();
56
	exec("/sbin/pfctl -t 'sshguard' -T show", $entries);
57

    
58
	/* If the client is in the lockout table, print an error, kill states, and exit */
59
	if (in_array($_SERVER['REMOTE_ADDR'], array_map('trim', $entries))) {
60
		if (!security_checks_disabled()) {
61
			/* They may never see the error since the connection will be cut off, but try to be nice anyhow. */
62
			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."));
63
			/* If they are locked out, they shouldn't have a state. Disconnect their connections. */
64
			$retval = pfSense_kill_states(utf8_encode($_SERVER['REMOTE_ADDR']));
65
			if (is_ipaddrv4($_SERVER['REMOTE_ADDR'])) {
66
				$retval = pfSense_kill_states("0.0.0.0/0", utf8_encode($_SERVER['REMOTE_ADDR']));
67
			} elseif (is_ipaddrv6($_SERVER['REMOTE_ADDR'])) {
68
				$retval = pfSense_kill_states("::", utf8_encode($_SERVER['REMOTE_ADDR']));
69
			}
70
			exit;
71
		}
72
		$security_passed = false;
73
	}
74
}
75

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

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

    
103
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
104
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
105
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
106
				$found_host = true;
107
				break;
108
			}
109
		}
110
	}
111

    
112
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
113
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
114
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
115
				$found_host = true;
116
				break;
117
			}
118
		}
119
	}
120

    
121
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
122
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
123
		foreach ($althosts as $ah) {
124
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
125
				$found_host = true;
126
				break;
127
			}
128
		}
129
	}
130

    
131
	if ($found_host == false) {
132
		if (!security_checks_disabled()) {
133
			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."));
134
			exit;
135
		}
136
		$security_passed = false;
137
	}
138
}
139

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

    
177
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
178
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
179
				foreach ($althosts as $ah) {
180
					if (strcasecmp($referrer_host, $ah) == 0) {
181
						$found_host = true;
182
						break;
183
					}
184
				}
185
			}
186

    
187
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
188
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
189
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
190
						$found_host = true;
191
						break;
192
					}
193
				}
194
			}
195

    
196
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
197
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
198
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
199
						$found_host = true;
200
						break;
201
					}
202
				}
203
			}
204

    
205
			if (!$found_host) {
206
				$interface_list_ips = get_configured_ip_addresses();
207
				foreach ($interface_list_ips as $ilips) {
208
					if (strcasecmp($referrer_host, $ilips) == 0) {
209
						$found_host = true;
210
						break;
211
					}
212
				}
213
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
214
				foreach ($interface_list_ipv6s as $ilipv6s) {
215
					$ilipv6s = explode('%', $ilipv6s)[0];
216
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
217
						$found_host = true;
218
						break;
219
					}
220
				}
221
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
222
					// allow SSH port forwarded connections and links from localhost
223
					$found_host = true;
224
				}
225
			}
226

    
227
			/* Fall back to probing active interface addresses rather than config.xml to allow
228
			 * changed addresses that have not yet been applied.
229
			 * See https://redmine.pfsense.org/issues/8822
230
			 */
231
			if (!$found_host) {
232
				$refifs = get_interface_arr();
233
				foreach ($refifs as $rif) {
234
					if (($referrer_host == find_interface_ip($rif)) ||
235
					    ($referrer_host == find_interface_ipv6($rif)) ||
236
					    ($referrer_host == find_interface_ipv6_ll($rif))) {
237
						$found_host = true;
238
						break;
239
					}
240
				}
241
			}
242
		}
243
		if ($found_host == false) {
244
			if (!security_checks_disabled()) {
245
				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 Access.");
246
				exit;
247
			}
248
			$security_passed = false;
249
		}
250
	} else {
251
		$security_passed = false;
252
	}
253
}
254

    
255
if (function_exists("display_error_form") && $security_passed) {
256
	/* Security checks passed, so it should be OK to turn them back on */
257
	restore_security_checks();
258
}
259
unset($security_passed);
260

    
261
$groupindex = index_groups();
262
$userindex = index_users();
263

    
264
function index_groups() {
265
	global $g, $debug, $config, $groupindex;
266

    
267
	$groupindex = array();
268

    
269
	if (is_array($config['system']['group'])) {
270
		$i = 0;
271
		foreach ($config['system']['group'] as $groupent) {
272
			$groupindex[$groupent['name']] = $i;
273
			$i++;
274
		}
275
	}
276

    
277
	return ($groupindex);
278
}
279

    
280
function index_users() {
281
	global $g, $debug, $config;
282

    
283
	if (is_array($config['system']['user'])) {
284
		$i = 0;
285
		foreach ($config['system']['user'] as $userent) {
286
			$userindex[$userent['name']] = $i;
287
			$i++;
288
		}
289
	}
290

    
291
	return ($userindex);
292
}
293

    
294
function & getUserEntry($name) {
295
	global $debug, $config, $userindex;
296
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
297

    
298
	if (isset($userindex[$name])) {
299
		return $config['system']['user'][$userindex[$name]];
300
	} elseif ($authcfg['type'] != "Local Database") {
301
		$user = array();
302
		$user['name'] = $name;
303
		return $user;
304
	}
305
}
306

    
307
function & getUserEntryByUID($uid) {
308
	global $debug, $config;
309

    
310
	if (is_array($config['system']['user'])) {
311
		foreach ($config['system']['user'] as & $user) {
312
			if ($user['uid'] == $uid) {
313
				return $user;
314
			}
315
		}
316
	}
317

    
318
	return false;
319
}
320

    
321
function & getGroupEntry($name) {
322
	global $debug, $config, $groupindex;
323
	if (isset($groupindex[$name])) {
324
		return $config['system']['group'][$groupindex[$name]];
325
	}
326
}
327

    
328
function & getGroupEntryByGID($gid) {
329
	global $debug, $config;
330

    
331
	if (is_array($config['system']['group'])) {
332
		foreach ($config['system']['group'] as & $group) {
333
			if ($group['gid'] == $gid) {
334
				return $group;
335
			}
336
		}
337
	}
338

    
339
	return false;
340
}
341

    
342
function get_user_privileges(& $user) {
343
	global $config, $_SESSION;
344

    
345
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
346
	$allowed_groups = array();
347

    
348
	$privs = $user['priv'];
349
	if (!is_array($privs)) {
350
		$privs = array();
351
	}
352

    
353
	// cache auth results for a short time to ease load on auth services & logs
354
	if (isset($config['system']['webgui']['auth_refresh_time'])) {
355
		$recheck_time = $config['system']['webgui']['auth_refresh_time'];
356
	} else {
357
		$recheck_time = 30;
358
	}
359

    
360
	if ($authcfg['type'] == "ldap") {
361
		if (isset($_SESSION["ldap_allowed_groups"]) &&
362
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
363
			$allowed_groups = $_SESSION["ldap_allowed_groups"];
364
		} else {
365
			$allowed_groups = @ldap_get_groups($user['name'], $authcfg);
366
			$_SESSION["ldap_allowed_groups"] = $allowed_groups;
367
			$_SESSION["auth_check_time"] = time();
368
		}
369
	} elseif ($authcfg['type'] == "radius") {
370
		if (isset($_SESSION["radius_allowed_groups"]) &&
371
		    (time() <= $_SESSION["auth_check_time"] + $recheck_time)) {
372
			$allowed_groups = $_SESSION["radius_allowed_groups"];
373
		} else {
374
			$allowed_groups = @radius_get_groups($_SESSION['user_radius_attributes']);
375
			$_SESSION["radius_allowed_groups"] = $allowed_groups;
376
			$_SESSION["auth_check_time"] = time();
377
		}
378
	}
379

    
380
	if (empty($allowed_groups)) {
381
		$allowed_groups = local_user_get_groups($user, true);
382
	}
383

    
384
	if (!is_array($allowed_groups)) {
385
		$allowed_groups = array('all');
386
	} else {
387
		$allowed_groups[] = 'all';
388
	}
389

    
390
	foreach ($allowed_groups as $name) {
391
		$group = getGroupEntry($name);
392
		if (is_array($group['priv'])) {
393
			$privs = array_merge($privs, $group['priv']);
394
		}
395
	}
396

    
397
	return $privs;
398
}
399

    
400
function userHasPrivilege($userent, $privid = false) {
401
	global $config;
402

    
403
	if (!$privid || !is_array($userent)) {
404
		return false;
405
	}
406

    
407
	$privs = get_user_privileges($userent);
408

    
409
	if (!is_array($privs)) {
410
		return false;
411
	}
412

    
413
	if (!in_array($privid, $privs)) {
414
		return false;
415
	}
416

    
417
	/* If someone is in admins group or is admin, do not honor the
418
	 * user-config-readonly privilege to prevent foot-shooting due to a
419
	 * bad privilege config.
420
	 * https://redmine.pfsense.org/issues/10492 */
421
	$userGroups = getUserGroups($userent['name'],
422
			auth_get_authserver($config['system']['webgui']['authmode']),
423
			$_SESSION['user_radius_attributes']);
424
	if (($privid == 'user-config-readonly') &&
425
	    (($userent['uid'] === "0") || (in_array('admins', $userGroups)))) {
426
		return false;
427
	}
428

    
429
	return true;
430
}
431

    
432
function local_backed($username, $passwd) {
433

    
434
	$user = getUserEntry($username);
435
	if (!$user) {
436
		return false;
437
	}
438

    
439
	if (is_account_disabled($username) || is_account_expired($username)) {
440
		return false;
441
	}
442

    
443
	if ($user['bcrypt-hash']) {
444
		if (password_verify($passwd, $user['bcrypt-hash'])) {
445
			return true;
446
		}
447
	}
448

    
449
	if ($user['sha512-hash']) {
450
		if (hash_equals($user['sha512-hash'], crypt($passwd, $user['sha512-hash']))) {
451
			return true;
452
		}
453
	}
454

    
455
	// pfSense < 2.3 password hashing, see https://redmine.pfsense.org/issues/4120
456
	if ($user['password']) {
457
		if (hash_equals($user['password'], crypt($passwd, $user['password']))) {
458
			return true;
459
		}
460
	}
461

    
462
	if ($user['md5-hash']) {
463
		if (hash_equals($user['md5-hash'], md5($passwd))) {
464
			return true;
465
		}
466
	}
467

    
468
	return false;
469
}
470

    
471
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
472
	global $config, $debug;
473

    
474
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
475
		/* Nothing to be done here */
476
		return;
477
	}
478

    
479
	foreach($u2del as $user) {
480
		if ($user['uid'] > 65000) {
481
			continue;
482
		} else if ($user['uid'] < 2000 && !in_array($user, $u2add)) {
483
			continue;
484
		}
485

    
486
		/*
487
		 * If a crontab was created to user, pw userdel will be
488
		 * interactive and can cause issues. Just remove crontab
489
		 * before run it when necessary
490
		 */
491
		unlink_if_exists("/var/cron/tabs/{$user['name']}");
492
		$cmd = "/usr/sbin/pw userdel -n " .
493
		    escapeshellarg($user['name']);
494
		if ($debug) {
495
			log_error(sprintf(gettext("Running: %s"), $cmd));
496
		}
497
		mwexec($cmd);
498
		local_group_del_user($user);
499

    
500
		$system_user = $config['system']['user'];
501
		for ($i = 0; $i < count($system_user); $i++) {
502
			if ($system_user[$i]['name'] == $user['name']) {
503
				log_error("Removing user: {$user['name']}");
504
				unset($config['system']['user'][$i]);
505
				break;
506
			}
507
		}
508
	}
509

    
510
	foreach($g2del as $group) {
511
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
512
			continue;
513
		}
514

    
515
		$cmd = "/usr/sbin/pw groupdel -g " .
516
		    escapeshellarg($group['name']);
517
		if ($debug) {
518
			log_error(sprintf(gettext("Running: %s"), $cmd));
519
		}
520
		mwexec($cmd);
521

    
522
		$system_group = $config['system']['group'];
523
		for ($i = 0; $i < count($system_group); $i++) {
524
			if ($system_group[$i]['name'] == $group['name']) {
525
				log_error("Removing group: {$group['name']}");
526
				unset($config['system']['group'][$i]);
527
				break;
528
			}
529
		}
530
	}
531

    
532
	foreach ($u2add as $user) {
533
		log_error("Adding user: {$user['name']}");
534
		$config['system']['user'][] = $user;
535
	}
536

    
537
	foreach ($g2add as $group) {
538
		log_error("Adding group: {$group['name']}");
539
		$config['system']['group'][] = $group;
540
	}
541

    
542
	/* Sort it alphabetically */
543
	usort($config['system']['user'], function($a, $b) {
544
		return strcmp($a['name'], $b['name']);
545
	});
546
	usort($config['system']['group'], function($a, $b) {
547
		return strcmp($a['name'], $b['name']);
548
	});
549

    
550
	write_config("Sync'd users and groups via XMLRPC");
551

    
552
	/* make sure the all group exists */
553
	$allgrp = getGroupEntryByGID(1998);
554
	local_group_set($allgrp, true);
555

    
556
	foreach ($u2add as $user) {
557
		local_user_set($user);
558
	}
559

    
560
	foreach ($g2add as $group) {
561
		local_group_set($group);
562
	}
563
}
564

    
565
function local_reset_accounts() {
566
	global $debug, $config;
567

    
568
	/* remove local users to avoid uid conflicts */
569
	$fd = popen("/usr/sbin/pw usershow -a", "r");
570
	if ($fd) {
571
		while (!feof($fd)) {
572
			$line = explode(":", fgets($fd));
573
			if ($line[0] != "admin") {
574
				if (!strncmp($line[0], "_", 1)) {
575
					continue;
576
				}
577
				if ($line[2] < 2000) {
578
					continue;
579
				}
580
				if ($line[2] > 65000) {
581
					continue;
582
				}
583
			}
584
			/*
585
			 * If a crontab was created to user, pw userdel will be interactive and
586
			 * can cause issues. Just remove crontab before run it when necessary
587
			 */
588
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
589
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
590
			if ($debug) {
591
				log_error(sprintf(gettext("Running: %s"), $cmd));
592
			}
593
			mwexec($cmd);
594
		}
595
		pclose($fd);
596
	}
597

    
598
	/* remove local groups to avoid gid conflicts */
599
	$gids = array();
600
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
601
	if ($fd) {
602
		while (!feof($fd)) {
603
			$line = explode(":", fgets($fd));
604
			if (!strncmp($line[0], "_", 1)) {
605
				continue;
606
			}
607
			if ($line[2] < 2000) {
608
				continue;
609
			}
610
			if ($line[2] > 65000) {
611
				continue;
612
			}
613
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
614
			if ($debug) {
615
				log_error(sprintf(gettext("Running: %s"), $cmd));
616
			}
617
			mwexec($cmd);
618
		}
619
		pclose($fd);
620
	}
621

    
622
	/* make sure the all group exists */
623
	$allgrp = getGroupEntryByGID(1998);
624
	local_group_set($allgrp, true);
625

    
626
	/* sync all local users */
627
	if (is_array($config['system']['user'])) {
628
		foreach ($config['system']['user'] as $user) {
629
			local_user_set($user);
630
		}
631
	}
632

    
633
	/* sync all local groups */
634
	if (is_array($config['system']['group'])) {
635
		foreach ($config['system']['group'] as $group) {
636
			local_group_set($group);
637
		}
638
	}
639
}
640

    
641
function local_user_set(& $user) {
642
	global $g, $debug;
643

    
644
	if (empty($user['sha512-hash']) && empty($user['bcrypt-hash']) && empty($user['password'])) {
645
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
646
		return;
647
	}
648

    
649

    
650
	$home_base = "/home/";
651
	$user_uid = $user['uid'];
652
	$user_name = $user['name'];
653
	$user_home = "{$home_base}{$user_name}";
654
	$user_shell = "/etc/rc.initial";
655
	$user_group = "nobody";
656

    
657
	// Ensure $home_base exists and is writable
658
	if (!is_dir($home_base)) {
659
		mkdir($home_base, 0755);
660
	}
661

    
662
	$lock_account = false;
663
	/* configure shell type */
664
	/* Cases here should be ordered by most privileged to least privileged. */
665
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
666
		$user_shell = "/bin/tcsh";
667
		$shell_access = true;
668
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
669
		$user_shell = "/usr/local/sbin/scponlyc";
670
	} elseif (userHasPrivilege($user, "user-copy-files")) {
671
		$user_shell = "/usr/local/bin/scponly";
672
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
673
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
674
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
675
		$user_shell = "/sbin/nologin";
676
	} else {
677
		$user_shell = "/sbin/nologin";
678
		$lock_account = true;
679
	}
680

    
681
	/* Lock out disabled or expired users, unless it's root/admin. */
682
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
683
		$user_shell = "/sbin/nologin";
684
		$lock_account = true;
685
	}
686

    
687
	/* root user special handling */
688
	if ($user_uid == 0) {
689
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
690
		if ($debug) {
691
			log_error(sprintf(gettext("Running: %s"), $cmd));
692
		}
693
		$fd = popen($cmd, "w");
694
		if (isset($user['bcrypt-hash'])) {
695
			fwrite($fd, $user['bcrypt-hash']);
696
		} elseif (isset($user['sha512-hash'])) {
697
			fwrite($fd, $user['sha512-hash']);
698
		} else {
699
			fwrite($fd, $user['password']);
700
		}
701
		pclose($fd);
702
		$user_group = "wheel";
703
		$user_home = "/root";
704
		$user_shell = "/etc/rc.initial";
705
		$shell_access = true;
706
	}
707

    
708
	/* read from pw db */
709
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
710
	$pwread = fgets($fd);
711
	pclose($fd);
712
	$userattrs = explode(":", trim($pwread));
713

    
714
	$skel_dir = '/etc/skel';
715

    
716
	/* determine add or mod */
717
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
718
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
719
	} else {
720
		$user_op = "usermod";
721
	}
722

    
723
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
724
	/* add or mod pw db */
725
	$cmd = "/usr/sbin/pw {$user_op} -q " .
726
			" -u " . escapeshellarg($user_uid) .
727
			" -n " . escapeshellarg($user_name) .
728
			" -g " . escapeshellarg($user_group) .
729
			" -s " . escapeshellarg($user_shell) .
730
			" -d " . escapeshellarg($user_home) .
731
			" -c " . escapeshellarg($comment) .
732
			" -H 0 2>&1";
733

    
734
	if ($debug) {
735
		log_error(sprintf(gettext("Running: %s"), $cmd));
736
	}
737
	$fd = popen($cmd, "w");
738
	if (isset($user['bcrypt-hash'])) {
739
		fwrite($fd, $user['bcrypt-hash']);
740
	} elseif (isset($user['sha512-hash'])) {
741
		fwrite($fd, $user['sha512-hash']);
742
	} else {
743
		fwrite($fd, $user['password']);
744
	}
745
	pclose($fd);
746

    
747
	/* create user directory if required */
748
	if (!is_dir($user_home)) {
749
		mkdir($user_home, 0700);
750
	}
751
	@chown($user_home, $user_name);
752
	@chgrp($user_home, $user_group);
753

    
754
	/* Make sure all users have last version of config files */
755
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
756
		$target = $user_home . '/' . substr(basename($dot_file), 3);
757
		@copy($dot_file, $target);
758
		@chown($target, $user_name);
759
		@chgrp($target, $user_group);
760
	}
761

    
762
	/* write out ssh authorized key file */
763
	if ($user['authorizedkeys']) {
764
		if (!is_dir("{$user_home}/.ssh")) {
765
			@mkdir("{$user_home}/.ssh", 0700);
766
			@chown("{$user_home}/.ssh", $user_name);
767
		}
768
		$keys = base64_decode($user['authorizedkeys']);
769
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
770
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
771
	} else {
772
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
773
	}
774

    
775
	if ($user['keephistory'] && $shell_access &&
776
	    !file_exists("{$user_home}/.keephistory")) {
777
		@touch("{$user_home}/.keephistory");
778
	} elseif (!$user['keephistory']) {
779
		unlink_if_exists("{$user_home}/.keephistory");
780
	}
781

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

    
785
}
786

    
787
function local_user_del($user) {
788
	global $debug;
789

    
790
	/* remove all memberships */
791
	local_user_set_groups($user);
792

    
793
	/* Don't remove /root */
794
	if ($user['uid'] != 0) {
795
		$rmhome = "-r";
796
	}
797

    
798
	/* read from pw db */
799
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
800
	$pwread = fgets($fd);
801
	pclose($fd);
802
	$userattrs = explode(":", trim($pwread));
803

    
804
	if ($userattrs[0] != $user['name']) {
805
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
806
		return;
807
	}
808

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

    
812
	if ($debug) {
813
		log_error(sprintf(gettext("Running: %s"), $cmd));
814
	}
815
	mwexec($cmd);
816

    
817
	/* Delete user from groups needs a call to write_config() */
818
	local_group_del_user($user);
819
}
820

    
821
function local_user_set_password(&$user, $password) {
822
	global $config;
823

    
824
	unset($user['password']);
825
	unset($user['md5-hash']);
826
	unset($user['sha512-hash']);
827
	unset($user['bcrypt-hash']);
828

    
829
	/* Default to bcrypt hashing if unset.
830
	 * See https://redmine.pfsense.org/issues/12855
831
	 */
832
	$hashalgo = isset($config['system']['webgui']['pwhash']) ? $config['system']['webgui']['pwhash'] : 'bcrypt';
833

    
834
	switch ($hashalgo) {
835
		case 'sha512':
836
			$salt = substr(bin2hex(random_bytes(16)),0,16);
837
			$user['sha512-hash'] = crypt($password, '$6$'. $salt . '$');
838
			break;
839
		case 'bcrypt':
840
		default:
841
			$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
842
			break;
843
	}
844

    
845
	if (($user['name'] == $config['hasync']['username']) &&
846
	    ($config['hasync']['adminsync'] == 'on')) {
847
		$config['hasync']['new_password'] = $password;
848
	}
849
}
850

    
851
function local_user_get_groups($user, $all = false) {
852
	global $debug, $config;
853

    
854
	$groups = array();
855
	if (!is_array($config['system']['group'])) {
856
		return $groups;
857
	}
858

    
859
	foreach ($config['system']['group'] as $group) {
860
		if ($all || (!$all && ($group['name'] != "all"))) {
861
			if (is_array($group['member'])) {
862
				if (in_array($user['uid'], $group['member'])) {
863
					$groups[] = $group['name'];
864
				}
865
			}
866
		}
867
	}
868

    
869
	if ($all) {
870
		$groups[] = "all";
871
	}
872

    
873
	sort($groups);
874

    
875
	return $groups;
876

    
877
}
878

    
879
function local_user_set_groups($user, $new_groups = NULL) {
880
	global $debug, $config, $groupindex, $userindex;
881

    
882
	if (!is_array($config['system']['group'])) {
883
		return;
884
	}
885

    
886
	$cur_groups = local_user_get_groups($user, true);
887
	$mod_groups = array();
888

    
889
	if (!is_array($new_groups)) {
890
		$new_groups = array();
891
	}
892

    
893
	if (!is_array($cur_groups)) {
894
		$cur_groups = array();
895
	}
896

    
897
	/* determine which memberships to add */
898
	foreach ($new_groups as $groupname) {
899
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
900
			continue;
901
		}
902
		$group = &$config['system']['group'][$groupindex[$groupname]];
903
		$group['member'][] = $user['uid'];
904
		$mod_groups[] = $group;
905

    
906
		/*
907
		 * If it's a new user, make sure it is added before try to
908
		 * add it as a member of a group
909
		 */
910
		if (!isset($userindex[$user['uid']])) {
911
			local_user_set($user);
912
		}
913
	}
914
	unset($group);
915

    
916
	/* determine which memberships to remove */
917
	foreach ($cur_groups as $groupname) {
918
		if (in_array($groupname, $new_groups)) {
919
			continue;
920
		}
921
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
922
			continue;
923
		}
924
		$group = &$config['system']['group'][$groupindex[$groupname]];
925
		if (is_array($group['member'])) {
926
			$index = array_search($user['uid'], $group['member']);
927
			array_splice($group['member'], $index, 1);
928
			$mod_groups[] = $group;
929
		}
930
	}
931
	unset($group);
932

    
933
	/* sync all modified groups */
934
	foreach ($mod_groups as $group) {
935
		local_group_set($group);
936
	}
937
}
938

    
939
function local_group_del_user($user) {
940
	global $config;
941

    
942
	if (!is_array($config['system']['group'])) {
943
		return;
944
	}
945

    
946
	foreach ($config['system']['group'] as $group) {
947
		if (is_array($group['member'])) {
948
			foreach ($group['member'] as $idx => $uid) {
949
				if ($user['uid'] == $uid) {
950
					unset($config['system']['group']['member'][$idx]);
951
				}
952
			}
953
		}
954
	}
955
}
956

    
957
function local_group_set($group, $reset = false) {
958
	global $debug;
959

    
960
	$group_name = $group['name'];
961
	$group_gid = $group['gid'];
962
	$group_members = '';
963

    
964
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
965
		$group_members = implode(",", $group['member']);
966
	}
967

    
968
	if (empty($group_name)) {
969
		return;
970
	}
971

    
972
	// If the group is now remote, make sure there is no local group with the same name
973
	if ($group['scope'] == "remote") {
974
		local_group_del($group);
975
		return;
976
	}
977

    
978
	/* determine add or mod */
979
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
980
		$group_op = "groupmod -l";
981
	} else {
982
		$group_op = "groupadd -n";
983
	}
984

    
985
	/* add or mod group db */
986
	$cmd = "/usr/sbin/pw {$group_op} " .
987
		escapeshellarg($group_name) .
988
		" -g " . escapeshellarg($group_gid) .
989
		" -M " . escapeshellarg($group_members) . " 2>&1";
990

    
991
	if ($debug) {
992
		log_error(sprintf(gettext("Running: %s"), $cmd));
993
	}
994

    
995
	mwexec($cmd);
996
}
997

    
998
function local_group_del($group) {
999
	global $debug;
1000

    
1001
	/* delete from group db */
1002
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
1003

    
1004
	if ($debug) {
1005
		log_error(sprintf(gettext("Running: %s"), $cmd));
1006
	}
1007
	mwexec($cmd);
1008
}
1009

    
1010
function ldap_test_connection($authcfg) {
1011
	if ($authcfg) {
1012
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1013
			$ldapproto = "ldaps";
1014
		} else {
1015
			$ldapproto = "ldap";
1016
		}
1017
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1018
		$ldapport = $authcfg['ldap_port'];
1019
		if (!empty($ldapport)) {
1020
			$ldapserver .= ":{$ldapport}";
1021
		}
1022
	} else {
1023
		return false;
1024
	}
1025

    
1026
	/* first check if there is even an LDAP server populated */
1027
	if (!$ldapserver) {
1028
		return false;
1029
	}
1030

    
1031
	/* connect and see if server is up */
1032
	$error = false;
1033
	if (!($ldap = ldap_connect($ldapserver))) {
1034
		$error = true;
1035
	}
1036

    
1037
	if ($error == true) {
1038
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
1039
		return false;
1040
	}
1041

    
1042
	/* Setup CA environment if needed. */
1043
	ldap_setup_caenv($ldap, $authcfg);
1044

    
1045
	return true;
1046
}
1047

    
1048
function ldap_setup_caenv($ldap, $authcfg) {
1049
	global $g;
1050
	require_once("certs.inc");
1051

    
1052
	unset($caref);
1053
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
1054
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
1055
		return;
1056
	} elseif ($authcfg['ldap_caref'] == "global") {
1057
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, "/etc/ssl/");
1058
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, "/etc/ssl/cert.pem");
1059
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1060
	} else {
1061
		$caref = lookup_ca($authcfg['ldap_caref']);
1062
		$cert_details = openssl_x509_parse(base64_decode($caref['crt']));
1063
		$param = array('caref' => $authcfg['ldap_caref']);
1064
		$cachain = ca_chain($param);
1065
		if (!$caref) {
1066
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
1067
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
1068
			ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1069
			return;
1070
		}
1071

    
1072
		$cert_path = "{$g['varrun_path']}/certs";
1073
		$cert_filename = "{$cert_path}/{$cert_details['hash']}.0";
1074
		safe_mkdir($cert_path);
1075
		unlink_if_exists($cert_filename);
1076
		file_put_contents($cert_filename, $cachain);
1077
		@chmod($cert_filename, 0600);
1078

    
1079
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1080
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, $cert_path);
1081
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, $cert_filename);
1082
	}
1083
}
1084

    
1085
function ldap_test_bind($authcfg) {
1086
	global $debug, $config, $g;
1087

    
1088
	if ($authcfg) {
1089
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1090
			$ldapproto = "ldaps";
1091
		} else {
1092
			$ldapproto = "ldap";
1093
		}
1094
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1095
		$ldapport = $authcfg['ldap_port'];
1096
		if (!empty($ldapport)) {
1097
			$ldapserver .= ":{$ldapport}";
1098
		}
1099
		$ldapbasedn = $authcfg['ldap_basedn'];
1100
		$ldapbindun = $authcfg['ldap_binddn'];
1101
		$ldapbindpw = $authcfg['ldap_bindpw'];
1102
		$ldapver = $authcfg['ldap_protver'];
1103
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1104
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1105
			$ldapanon = true;
1106
		} else {
1107
			$ldapanon = false;
1108
		}
1109
	} else {
1110
		return false;
1111
	}
1112

    
1113
	/* first check if there is even an LDAP server populated */
1114
	if (!$ldapserver) {
1115
		return false;
1116
	}
1117

    
1118
	/* connect and see if server is up */
1119
	$error = false;
1120
	if (!($ldap = ldap_connect($ldapserver))) {
1121
		$error = true;
1122
	}
1123

    
1124
	if ($error == true) {
1125
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1126
		return false;
1127
	}
1128

    
1129
	/* Setup CA environment if needed. */
1130
	ldap_setup_caenv($ldap, $authcfg);
1131

    
1132
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1133
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1134
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1135
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1136
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1137

    
1138
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1139
		if (!(@ldap_start_tls($ldap))) {
1140
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1141
			@ldap_close($ldap);
1142
			return false;
1143
		}
1144
	}
1145

    
1146
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1147
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1148
	if ($ldapanon == true) {
1149
		if (!($res = @ldap_bind($ldap))) {
1150
			@ldap_close($ldap);
1151
			return false;
1152
		}
1153
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1154
		@ldap_close($ldap);
1155
		return false;
1156
	}
1157

    
1158
	@ldap_unbind($ldap);
1159

    
1160
	return true;
1161
}
1162

    
1163
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1164
	global $debug, $config, $g;
1165

    
1166
	if (!function_exists("ldap_connect")) {
1167
		return;
1168
	}
1169

    
1170
	$ous = array();
1171

    
1172
	if ($authcfg) {
1173
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1174
			$ldapproto = "ldaps";
1175
		} else {
1176
			$ldapproto = "ldap";
1177
		}
1178
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1179
		$ldapport = $authcfg['ldap_port'];
1180
		if (!empty($ldapport)) {
1181
			$ldapserver .= ":{$ldapport}";
1182
		}
1183
		$ldapbasedn = $authcfg['ldap_basedn'];
1184
		$ldapbindun = $authcfg['ldap_binddn'];
1185
		$ldapbindpw = $authcfg['ldap_bindpw'];
1186
		$ldapver = $authcfg['ldap_protver'];
1187
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1188
			$ldapanon = true;
1189
		} else {
1190
			$ldapanon = false;
1191
		}
1192
		$ldapname = $authcfg['name'];
1193
		$ldapfallback = false;
1194
		$ldapscope = $authcfg['ldap_scope'];
1195
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1196
	} else {
1197
		return false;
1198
	}
1199

    
1200
	/* first check if there is even an LDAP server populated */
1201
	if (!$ldapserver) {
1202
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1203
		return $ous;
1204
	}
1205

    
1206
	/* connect and see if server is up */
1207
	$error = false;
1208
	if (!($ldap = ldap_connect($ldapserver))) {
1209
		$error = true;
1210
	}
1211

    
1212
	if ($error == true) {
1213
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1214
		return $ous;
1215
	}
1216

    
1217
	/* Setup CA environment if needed. */
1218
	ldap_setup_caenv($ldap, $authcfg);
1219

    
1220
	$ldapfilter = "(|(ou=*)(cn=Users))";
1221

    
1222
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1223
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1224
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1225
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1226
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1227

    
1228
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1229
		if (!(@ldap_start_tls($ldap))) {
1230
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1231
			@ldap_close($ldap);
1232
			return false;
1233
		}
1234
	}
1235

    
1236
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1237
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1238
	if ($ldapanon == true) {
1239
		if (!($res = @ldap_bind($ldap))) {
1240
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1241
			@ldap_close($ldap);
1242
			return $ous;
1243
		}
1244
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1245
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1246
		@ldap_close($ldap);
1247
		return $ous;
1248
	}
1249

    
1250
	if ($ldapscope == "one") {
1251
		$ldapfunc = "ldap_list";
1252
	} else {
1253
		$ldapfunc = "ldap_search";
1254
	}
1255

    
1256
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1257
	$info = @ldap_get_entries($ldap, $search);
1258

    
1259
	if (is_array($info)) {
1260
		foreach ($info as $inf) {
1261
			if (!$show_complete_ou) {
1262
				$inf_split = explode(",", $inf['dn']);
1263
				$ou = $inf_split[0];
1264
				$ou = str_replace("OU=", "", $ou);
1265
				$ou = str_replace("CN=", "", $ou);
1266
			} else {
1267
				if ($inf['dn']) {
1268
					$ou = $inf['dn'];
1269
				}
1270
			}
1271
			if ($ou) {
1272
				$ous[] = $ou;
1273
			}
1274
		}
1275
	}
1276

    
1277
	@ldap_unbind($ldap);
1278

    
1279
	return $ous;
1280
}
1281

    
1282
function ldap_get_groups($username, $authcfg) {
1283
	global $debug, $config;
1284

    
1285
	if (!function_exists("ldap_connect")) {
1286
		return array();
1287
	}
1288

    
1289
	if (!$username) {
1290
		return array();
1291
	}
1292

    
1293
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1294
		$username_split = explode("@", $username);
1295
		$username = $username_split[0];
1296
	}
1297

    
1298
	if (stristr($username, "\\")) {
1299
		$username_split = explode("\\", $username);
1300
		$username = $username_split[0];
1301
	}
1302

    
1303
	//log_error("Getting LDAP groups for {$username}.");
1304
	if ($authcfg) {
1305
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1306
			$ldapproto = "ldaps";
1307
		} else {
1308
			$ldapproto = "ldap";
1309
		}
1310
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1311
		$ldapport = $authcfg['ldap_port'];
1312
		if (!empty($ldapport)) {
1313
			$ldapserver .= ":{$ldapport}";
1314
		}
1315
		$ldapbasedn = $authcfg['ldap_basedn'];
1316
		$ldapbindun = $authcfg['ldap_binddn'];
1317
		$ldapbindpw = $authcfg['ldap_bindpw'];
1318
		$ldapauthcont = $authcfg['ldap_authcn'];
1319
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1320
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1321
		$ldaptype = "";
1322
		$ldapver = $authcfg['ldap_protver'];
1323
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1324
			$ldapanon = true;
1325
		} else {
1326
			$ldapanon = false;
1327
		}
1328
		$ldapname = $authcfg['name'];
1329
		$ldapfallback = false;
1330
		$ldapscope = $authcfg['ldap_scope'];
1331
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1332
	} else {
1333
		return array();
1334
	}
1335

    
1336
	if (isset($authcfg['ldap_rfc2307'])) {
1337
		$ldapdn = $ldapbasedn;
1338
	} else {
1339
		$ldapdn = $_SESSION['ldapdn'];
1340
	}
1341

    
1342
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1343
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1344
	$memberof = array();
1345

    
1346
	/* connect and see if server is up */
1347
	$error = false;
1348
	if (!($ldap = ldap_connect($ldapserver))) {
1349
		$error = true;
1350
	}
1351

    
1352
	if ($error == true) {
1353
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1354
		return $memberof;
1355
	}
1356

    
1357
	/* Setup CA environment if needed. */
1358
	ldap_setup_caenv($ldap, $authcfg);
1359

    
1360
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1361
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1362
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1363
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1364
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1365

    
1366
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1367
		if (!(@ldap_start_tls($ldap))) {
1368
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1369
			@ldap_close($ldap);
1370
			return array();
1371
		}
1372
	}
1373

    
1374
	/* bind as user that has rights to read group attributes */
1375
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1376
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1377
	if ($ldapanon == true) {
1378
		if (!($res = @ldap_bind($ldap))) {
1379
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1380
			@ldap_close($ldap);
1381
			return array();
1382
		}
1383
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1384
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1385
		@ldap_close($ldap);
1386
		return $memberof;
1387
	}
1388

    
1389
	/* get groups from DN found */
1390
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1391
	/* since we know the DN is in $_SESSION['ldapdn'] */
1392
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1393
	if ($ldapscope == "one") {
1394
		$ldapfunc = "ldap_list";
1395
	} else {
1396
		$ldapfunc = "ldap_search";
1397
	}
1398

    
1399
	if (isset($authcfg['ldap_rfc2307'])) {
1400
		if (isset($authcfg['ldap_rfc2307_userdn'])) {
1401
			$ldac_splits = explode(";", $ldapauthcont);
1402
			foreach ($ldac_splits as $i => $ldac_split) {
1403
				$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1404
				$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1405
				$ldapfilter = "({$ldapnameattribute}={$username})";
1406
				if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1407
					$ldapdn = $ldac_split;
1408
				} else {
1409
					$ldapdn = $ldapsearchbasedn;
1410
				}
1411
				$usersearch = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1412
				$userinfo = @ldap_get_entries($ldap, $usersearch);
1413
			}
1414
			$username = $userinfo[0]['dn'];
1415
		}
1416
		$ldapfilter = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1417
	} else {
1418
		$ldapfilter = "({$ldapnameattribute}={$username})";
1419
	}
1420

    
1421
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1422
	$info = @ldap_get_entries($ldap, $search);
1423

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

    
1426
	if (is_array($gresults)) {
1427
		/* Iterate through the groups and throw them into an array */
1428
		foreach ($gresults as $grp) {
1429
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1430
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1431
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1432
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1433
			}
1434
		}
1435
	}
1436

    
1437
	/* Time to close LDAP connection */
1438
	@ldap_unbind($ldap);
1439

    
1440
	$groups = print_r($memberof, true);
1441

    
1442
	//log_error("Returning groups ".$groups." for user $username");
1443

    
1444
	return $memberof;
1445
}
1446

    
1447
function ldap_format_host($host) {
1448
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1449
}
1450

    
1451
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1452
	global $debug, $config;
1453

    
1454
	if (!$username) {
1455
		$attributes['error_message'] = gettext("Invalid Login.");
1456
		return false;
1457
	}
1458

    
1459
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1460
		$attributes['error_message'] = gettext("Invalid credentials.");
1461
		return false;
1462
	}
1463

    
1464
	if (!function_exists("ldap_connect")) {
1465
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1466
		$attributes['error_message'] = gettext("Internal error during authentication.");
1467
		return null;
1468
	}
1469

    
1470
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1471
		$username_split = explode("@", $username);
1472
		$username = $username_split[0];
1473
	}
1474
	if (stristr($username, "\\")) {
1475
		$username_split = explode("\\", $username);
1476
		$username = $username_split[0];
1477
	}
1478

    
1479
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1480

    
1481
	if ($authcfg) {
1482
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1483
			$ldapproto = "ldaps";
1484
		} else {
1485
			$ldapproto = "ldap";
1486
		}
1487
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1488
		$ldapport = $authcfg['ldap_port'];
1489
		if (!empty($ldapport)) {
1490
			$ldapserver .= ":{$ldapport}";
1491
		}
1492
		$ldapbasedn = $authcfg['ldap_basedn'];
1493
		$ldapbindun = $authcfg['ldap_binddn'];
1494
		$ldapbindpw = $authcfg['ldap_bindpw'];
1495
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1496
			$ldapanon = true;
1497
		} else {
1498
			$ldapanon = false;
1499
		}
1500
		$ldapauthcont = $authcfg['ldap_authcn'];
1501
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1502
		$ldapgroupattribute = $authcfg['ldap_attr_member'];
1503
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1504
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1505
		$ldapfilter = "";
1506
		if (!$ldapextendedqueryenabled) {
1507
			$ldapfilter = "({$ldapnameattribute}={$username})";
1508
		} else {
1509
			if (isset($authcfg['ldap_rfc2307'])) {
1510
				$ldapfilter = "({$ldapnameattribute}={$username})";
1511
				$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1512
			} else {
1513
				$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1514
			}
1515
		}
1516
		$ldaptype = "";
1517
		$ldapver = $authcfg['ldap_protver'];
1518
		$ldapname = $authcfg['name'];
1519
		$ldapscope = $authcfg['ldap_scope'];
1520
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1521
	} else {
1522
		return null;
1523
	}
1524

    
1525
	/* first check if there is even an LDAP server populated */
1526
	if (!$ldapserver) {
1527
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1528
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1529
		return null;
1530
	}
1531

    
1532
	/* Make sure we can connect to LDAP */
1533
	$error = false;
1534
	if (!($ldap = ldap_connect($ldapserver))) {
1535
		$error = true;
1536
	}
1537

    
1538
	/* Setup CA environment if needed. */
1539
	ldap_setup_caenv($ldap, $authcfg);
1540

    
1541
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1542
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1543
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1544
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1545
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1546

    
1547
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1548
		if (!(@ldap_start_tls($ldap))) {
1549
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1550
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1551
			@ldap_close($ldap);
1552
			return null;
1553
		}
1554
	}
1555

    
1556
	if ($error == true) {
1557
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1558
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1559
		return null;
1560
	}
1561

    
1562
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1563
	$error = false;
1564
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1565
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1566
	if ($ldapanon == true) {
1567
		if (!($res = @ldap_bind($ldap))) {
1568
			$error = true;
1569
		}
1570
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1571
		$error = true;
1572
	}
1573

    
1574
	if ($error == true) {
1575
		@ldap_close($ldap);
1576
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1577
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1578
		return null;
1579
	}
1580

    
1581
	/* Get LDAP Authcontainers and split em up. */
1582
	$ldac_splits = explode(";", $ldapauthcont);
1583

    
1584
	/* setup the usercount so we think we haven't found anyone yet */
1585
	$usercount = 0;
1586

    
1587
	/*****************************************************************/
1588
	/*  We first find the user based on username and filter          */
1589
	/*  then, once we find the first occurrence of that person       */
1590
	/*  we set session variables to point to the OU and DN of the    */
1591
	/*  person.  To later be used by ldap_get_groups.                */
1592
	/*  that way we don't have to search twice.                      */
1593
	/*****************************************************************/
1594
	if ($debug) {
1595
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1596
	}
1597
	/* Iterate through the user containers for search */
1598
	foreach ($ldac_splits as $i => $ldac_split) {
1599
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1600
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1601
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1602
		/* Make sure we just use the first user we find */
1603
		if ($debug) {
1604
			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)));
1605
		}
1606
		if ($ldapscope == "one") {
1607
			$ldapfunc = "ldap_list";
1608
		} else {
1609
			$ldapfunc = "ldap_search";
1610
		}
1611
		/* Support legacy auth container specification. */
1612
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1613
			$ldapdn = $ldac_split;
1614
		} else {
1615
			$ldapdn = $ldapsearchbasedn;
1616
		}
1617
		$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1618
		if (!$search) {
1619
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1620
			continue;
1621
		}
1622
		if (isset($authcfg['ldap_rfc2307']) && isset($ldapgroupfilter)) {
1623
			if (isset($authcfg['ldap_rfc2307_userdn'])) {
1624
				$info = ldap_get_entries($ldap, $search);
1625
				$username = $info[0]['dn'];
1626
			}
1627
			$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1628
			$groupsearch = @$ldapfunc($ldap, $ldapdn, $ldapgroupfilter);
1629
		}
1630

    
1631
		if (isset($ldapgroupfilter) && !$groupsearch) {
1632
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1633
			continue;
1634
		}
1635
		if (isset($groupsearch)) {
1636
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1637
			if ($debug) {
1638
				log_auth(sprintf(gettext("LDAP group search: %s results."), $validgroup));
1639
			}
1640
		}
1641
		$info = ldap_get_entries($ldap, $search);
1642
		$matches = $info['count'];
1643
		if ($matches == 1) {
1644
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1645
			$_SESSION['ldapou'] = $ldac_split[$i];
1646
			$_SESSION['ldapon'] = "true";
1647
			$usercount = 1;
1648
			break;
1649
		}
1650
	}
1651

    
1652
	if ($usercount != 1) {
1653
		@ldap_unbind($ldap);
1654
		if ($debug) {
1655
			if ($usercount === 0) {
1656
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1657
			} else {
1658
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1659
			}
1660
		}
1661
		$attributes['error_message'] = gettext("Invalid login specified.");
1662
		return false;
1663
	}
1664

    
1665
	/* Now lets bind as the user we found */
1666
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1667
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1668
		if ($debug) {
1669
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1670
		}
1671
		@ldap_unbind($ldap);
1672
		return false;
1673
	}
1674

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

    
1680
	if ($debug && isset($ldapgroupfilter) && $validgroup < 1) {
1681
		log_auth(sprintf(gettext('Logged in successfully as %1$s but did not match any field in extended query.'), $username));
1682
	}
1683

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

    
1687
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1688
		return false;
1689
	}
1690

    
1691
	return true;
1692
}
1693

    
1694
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1695
	global $debug, $config;
1696
	$ret = false;
1697

    
1698
	require_once("Auth/RADIUS.php");
1699
	require_once("Crypt/CHAP.php");
1700

    
1701
	if ($authcfg) {
1702
		$radiusservers = array();
1703
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1704
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1705
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1706
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1707
		if(isset($authcfg['radius_protocol'])) {
1708
			$radius_protocol = $authcfg['radius_protocol'];
1709
		} else {
1710
			$radius_protocol = 'PAP';
1711
		}
1712
	} else {
1713
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1714
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1715
		return null;
1716
	}
1717

    
1718
	// Create our instance
1719
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1720
	$rauth = new $classname($username, $password);
1721

    
1722
	/* Add new servers to our instance */
1723
	foreach ($radiusservers as $radsrv) {
1724
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1725
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1726
	}
1727

    
1728
	// Construct data package
1729
	$rauth->username = $username;
1730
	switch ($radius_protocol) {
1731
		case 'CHAP_MD5':
1732
		case 'MSCHAPv1':
1733
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1734
			$crpt = new $classname;
1735
			$crpt->username = $username;
1736
			$crpt->password = $password;
1737
			$rauth->challenge = $crpt->challenge;
1738
			$rauth->chapid = $crpt->chapid;
1739
			$rauth->response = $crpt->challengeResponse();
1740
			$rauth->flags = 1;
1741
			break;
1742

    
1743
		case 'MSCHAPv2':
1744
			$crpt = new Crypt_CHAP_MSv2;
1745
			$crpt->username = $username;
1746
			$crpt->password = $password;
1747
			$rauth->challenge = $crpt->authChallenge;
1748
			$rauth->peerChallenge = $crpt->peerChallenge;
1749
			$rauth->chapid = $crpt->chapid;
1750
			$rauth->response = $crpt->challengeResponse();
1751
			break;
1752

    
1753
		default:
1754
			$rauth->password = $password;
1755
			break;
1756
	}
1757

    
1758
	if (PEAR::isError($rauth->start())) {
1759
		$ret = null;
1760
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1761
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1762
	} else {
1763
		$nasid = $attributes['nas_identifier'];
1764
		$nasip = $authcfg['radius_nasip_attribute'];
1765
		if (empty($nasid)) {
1766
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1767
		}
1768
		if (!is_ipaddr($nasip)) {
1769
			$nasip = get_interface_ip($nasip);
1770

    
1771
			if (!is_ipaddr($nasip)) {
1772
				/* use first interface with IP as fallback for NAS-IP-Address
1773
				 * see https://redmine.pfsense.org/issues/11109 */
1774
				foreach (get_configured_interface_list() as $if) {
1775
					$nasip = get_interface_ip($if);
1776
					if (is_ipaddr($nasip)) {
1777
						break;
1778
					}
1779
				}
1780
			}
1781
		}
1782
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1783

    
1784
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1785
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1786

    
1787
		if(!empty($attributes['calling_station_id'])) {
1788
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1789
		}
1790
		// Carefully check that interface has a MAC address
1791
		if(!empty($nasmac)) {
1792
			$nasmac = mac_format($nasmac);
1793
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1794
		}
1795
		if(!empty($attributes['nas_port_type'])) {
1796
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1797
		}
1798
		if(!empty($attributes['nas_port'])) {
1799
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1800
		}
1801
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1802
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1803
		}
1804
	}
1805

    
1806
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1807

    
1808
	/* Send request */
1809
	$result = $rauth->send();
1810
	if (PEAR::isError($result)) {
1811
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1812
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1813
		$ret = null;
1814
	} else if ($result === true) {
1815
		$ret = true;
1816
	} else {
1817
		$ret = false;
1818
	}
1819

    
1820

    
1821
	// Get attributes, even if auth failed.
1822
	if ($rauth->getAttributes()) {
1823
	$attributes = array_merge($attributes,$rauth->listAttributes());
1824

    
1825
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1826
	if (!empty($attributes['session_terminate_time'])) {
1827
			$stt = &$attributes['session_terminate_time'];
1828
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1829
		}
1830
	}
1831

    
1832
	// close OO RADIUS_AUTHENTICATION
1833
	$rauth->close();
1834

    
1835
	return $ret;
1836
}
1837

    
1838
/*
1839
	$attributes must contain a "class" key containing the groups and local
1840
	groups must exist to match.
1841
*/
1842
function radius_get_groups($attributes) {
1843
	$groups = array();
1844
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1845
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1846
		$groups = array();
1847
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1848
			foreach ($attributes['class'] as $class) {
1849
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1850
			}
1851
		}
1852

    
1853
		foreach ($groups as & $grp) {
1854
			$grp = trim($grp);
1855
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1856
				$grp = substr($grp, 3);
1857
			}
1858
		}
1859
	}
1860
	return $groups;
1861
}
1862

    
1863
function get_user_expiration_date($username) {
1864
	$user = getUserEntry($username);
1865
	if ($user['expires']) {
1866
		return $user['expires'];
1867
	}
1868
}
1869

    
1870
function is_account_expired($username) {
1871
	$expirydate = get_user_expiration_date($username);
1872
	if ($expirydate) {
1873
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1874
			return true;
1875
		}
1876
	}
1877

    
1878
	return false;
1879
}
1880

    
1881
function is_account_disabled($username) {
1882
	$user = getUserEntry($username);
1883
	if (isset($user['disabled'])) {
1884
		return true;
1885
	}
1886

    
1887
	return false;
1888
}
1889

    
1890
function get_user_settings($username) {
1891
	global $config;
1892
	$settings = array();
1893
	$settings['widgets'] = $config['widgets'];
1894
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1895
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1896
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1897
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1898
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1899
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1900
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1901
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1902
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1903
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1904
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1905
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1906
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1907
	$user = getUserEntry($username);
1908
	if (isset($user['customsettings'])) {
1909
		$settings['customsettings'] = true;
1910
		if (isset($user['widgets'])) {
1911
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1912
			$settings['widgets'] = $user['widgets'];
1913
		}
1914
		if (isset($user['dashboardcolumns'])) {
1915
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1916
		}
1917
		if (isset($user['webguicss'])) {
1918
			$settings['webgui']['webguicss'] = $user['webguicss'];
1919
		}
1920
		if (isset($user['webguihostnamemenu'])) {
1921
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1922
		}
1923
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1924
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1925
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1926
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1927
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1928
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1929
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1930
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1931
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1932
	} else {
1933
		$settings['customsettings'] = false;
1934
	}
1935

    
1936
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1937
		$settings['webgui']['dashboardcolumns'] = 2;
1938
	}
1939

    
1940
	return $settings;
1941
}
1942

    
1943
function save_widget_settings($username, $settings, $message = "") {
1944
	global $config, $userindex;
1945
	$user = getUserEntry($username);
1946

    
1947
	if (strlen($message) > 0) {
1948
		$msgout = $message;
1949
	} else {
1950
		$msgout = gettext("Widget configuration has been changed.");
1951
	}
1952

    
1953
	if (isset($user['customsettings'])) {
1954
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1955
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1956
	} else {
1957
		$config['widgets'] = $settings;
1958
		write_config($msgout);
1959
	}
1960
}
1961

    
1962
function auth_get_authserver($name) {
1963
	global $config;
1964

    
1965
	if (is_array($config['system']['authserver'])) {
1966
		foreach ($config['system']['authserver'] as $authcfg) {
1967
			if ($authcfg['name'] == $name) {
1968
				return $authcfg;
1969
			}
1970
		}
1971
	}
1972
	if ($name == "Local Database") {
1973
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1974
	}
1975
}
1976

    
1977
function auth_get_authserver_list() {
1978
	global $config;
1979

    
1980
	$list = array();
1981

    
1982
	if (is_array($config['system']['authserver'])) {
1983
		foreach ($config['system']['authserver'] as $authcfg) {
1984
			/* Add support for disabled entries? */
1985
			$list[$authcfg['name']] = $authcfg;
1986
		}
1987
	}
1988

    
1989
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1990
	return $list;
1991
}
1992

    
1993
function getUserGroups($username, $authcfg, &$attributes = array()) {
1994
	global $config;
1995

    
1996
	$allowed_groups = array();
1997

    
1998
	switch ($authcfg['type']) {
1999
		case 'ldap':
2000
			$allowed_groups = @ldap_get_groups($username, $authcfg);
2001
			break;
2002
		case 'radius':
2003
			$allowed_groups = @radius_get_groups($attributes);
2004
			break;
2005
		default:
2006
			$user = getUserEntry($username);
2007
			$allowed_groups = @local_user_get_groups($user, true);
2008
			break;
2009
	}
2010

    
2011
	$member_groups = array();
2012
	if (is_array($config['system']['group'])) {
2013
		foreach ($config['system']['group'] as $group) {
2014
			if (in_array($group['name'], $allowed_groups)) {
2015
				$member_groups[] = $group['name'];
2016
			}
2017
		}
2018
	}
2019

    
2020
	return $member_groups;
2021
}
2022

    
2023
/*
2024
Possible return values :
2025
true : authentication worked
2026
false : authentication failed (invalid login/password, not enough permission, etc...)
2027
null : error during authentication process (unable to reach remote server, etc...)
2028
*/
2029
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
2030

    
2031
	if (is_array($username) || is_array($password)) {
2032
		return false;
2033
	}
2034

    
2035
	if (!$authcfg) {
2036
		return local_backed($username, $password, $attributes);
2037
	}
2038

    
2039
	$authenticated = false;
2040
	switch ($authcfg['type']) {
2041
		case 'ldap':
2042
			try {
2043
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
2044
			} catch (Exception $e) {
2045
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
2046
			}
2047
			break;
2048

    
2049
			break;
2050
		case 'radius':
2051
			try {
2052
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
2053
			} catch (Exception $e) {
2054
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
2055
			}
2056
			break;
2057
		default:
2058
			/* lookup user object by name */
2059
			try {
2060
				$authenticated = local_backed($username, $password, $attributes);
2061
			} catch (Exception $e) {
2062
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
2063
			}
2064
			break;
2065
		}
2066

    
2067
	return $authenticated;
2068
}
2069

    
2070
function session_auth() {
2071
	global $config, $_SESSION, $page;
2072

    
2073
	// Handle HTTPS httponly and secure flags
2074
	$currentCookieParams = session_get_cookie_params();
2075
	session_set_cookie_params(
2076
		$currentCookieParams["lifetime"],
2077
		$currentCookieParams["path"],
2078
		NULL,
2079
		($config['system']['webgui']['protocol'] == "https"),
2080
		true
2081
	);
2082

    
2083
	phpsession_begin();
2084

    
2085
	// Detect protocol change
2086
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2087
		phpsession_end();
2088
		return false;
2089
	}
2090

    
2091
	/* Validate incoming login request */
2092
	$attributes = array('nas_identifier' => 'webConfigurator-' . gethostname());
2093
	if (isset($_POST['login']) && !empty($_POST['usernamefld'])) {
2094
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2095
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
2096
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
2097
			// Generate a new id to avoid session fixation
2098
			session_regenerate_id();
2099
			$_SESSION['Logged_In'] = "True";
2100
			$_SESSION['remoteauth'] = $remoteauth;
2101
			if ($remoteauth) {
2102
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
2103
					$_SESSION['authsource'] = "Local Database";
2104
				} else {
2105
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
2106
				}
2107
			} else {
2108
				$_SESSION['authsource'] = 'Local Database Fallback';
2109
			}
2110
			$_SESSION['Username'] = $_POST['usernamefld'];
2111
			$_SESSION['user_radius_attributes'] = $attributes;
2112
			$_SESSION['last_access'] = time();
2113
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
2114
			phpsession_end(true);
2115
			if (!isset($config['system']['webgui']['quietlogin'])) {
2116
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2117
			}
2118
			if (isset($_POST['postafterlogin'])) {
2119
				return true;
2120
			} else {
2121
				if (empty($page)) {
2122
					$page = "/";
2123
				}
2124
				header("Location: {$page}");
2125
			}
2126
			exit;
2127
		} else {
2128
			/* give the user an error message */
2129
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
2130
			log_auth(sprintf(gettext("webConfigurator authentication error for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2131
			if (isAjax()) {
2132
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
2133
				return;
2134
			}
2135
		}
2136
	}
2137

    
2138
	/* Show login page if they aren't logged in */
2139
	if (empty($_SESSION['Logged_In'])) {
2140
		phpsession_end(true);
2141
		return false;
2142
	}
2143

    
2144
	/* If session timeout isn't set, we don't mark sessions stale */
2145
	if (!isset($config['system']['webgui']['session_timeout'])) {
2146
		/* Default to 4 hour timeout if one is not set */
2147
		if ($_SESSION['last_access'] < (time() - 14400)) {
2148
			$_POST['logout'] = true;
2149
			$_SESSION['Logout'] = true;
2150
		} else {
2151
			$_SESSION['last_access'] = time();
2152
		}
2153
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2154
		/* only update if it wasn't ajax */
2155
		if (!isAjax()) {
2156
			$_SESSION['last_access'] = time();
2157
		}
2158
	} else {
2159
		/* Check for stale session */
2160
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2161
			$_POST['logout'] = true;
2162
			$_SESSION['Logout'] = true;
2163
		} else {
2164
			/* only update if it wasn't ajax */
2165
			if (!isAjax()) {
2166
				$_SESSION['last_access'] = time();
2167
			}
2168
		}
2169
	}
2170

    
2171
	/* user hit the logout button */
2172
	if (isset($_POST['logout'])) {
2173

    
2174
		if ($_SESSION['Logout']) {
2175
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2176
		} else {
2177
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2178
		}
2179

    
2180
		/* wipe out $_SESSION */
2181
		$_SESSION = array();
2182

    
2183
		if (isset($_COOKIE[session_name()])) {
2184
			setcookie(session_name(), '', time()-42000, '/');
2185
		}
2186

    
2187
		/* and destroy it */
2188
		phpsession_destroy();
2189

    
2190
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2191
		$scriptElms = count($scriptName);
2192
		$scriptName = $scriptName[$scriptElms-1];
2193

    
2194
		if (isAjax()) {
2195
			return false;
2196
		}
2197

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

    
2201
		return false;
2202
	}
2203

    
2204
	/*
2205
	 * this is for debugging purpose if you do not want to use Ajax
2206
	 * to submit a HTML form. It basically disables the observation
2207
	 * of the submit event and hence does not trigger Ajax.
2208
	 */
2209
	if ($_REQUEST['disable_ajax']) {
2210
		$_SESSION['NO_AJAX'] = "True";
2211
	}
2212

    
2213
	/*
2214
	 * Same to re-enable Ajax.
2215
	 */
2216
	if ($_REQUEST['enable_ajax']) {
2217
		unset($_SESSION['NO_AJAX']);
2218
	}
2219
	phpsession_end(true);
2220
	return true;
2221
}
2222

    
2223
function print_credit() {
2224
	global $g;
2225

    
2226
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_label"] . '</a>' .
2227
			gettext(' is developed and maintained by ') .
2228
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2229
			'<a target="_blank" href="https://pfsense.org/license">' .
2230
			gettext(' View license.') . '</a>';
2231
}
2232
function get_user_remote_address() {
2233
	$remote_address = $_SERVER['REMOTE_ADDR'];
2234
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2235
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2236
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2237
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2238
	}
2239
	return $remote_address;
2240
}
2241
function get_user_remote_authsource() {
2242
	$authsource = "";
2243
	if (!empty($_SESSION['authsource'])) {
2244
		$authsource .= " ({$_SESSION['authsource']})";
2245
	}
2246
	return $authsource;
2247
}
2248

    
2249
function set_pam_auth() {
2250
	global $config;
2251

    
2252
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2253

    
2254
	unlink_if_exists("/etc/radius.conf");
2255
	unlink_if_exists("/var/etc/pam_ldap.conf");
2256
	unlink_if_exists("/var/etc/pam_ldap_ca.crt");
2257

    
2258
	$header = "# This file is automatically generated. Do not edit.\n\n";
2259
	$pam_sshd =<<<EOD
2260
# auth
2261
auth		required	pam_unix.so		no_warn try_first_pass
2262

    
2263
# account
2264
account		required	pam_nologin.so
2265
account		required	pam_login_access.so
2266
account		required	pam_unix.so
2267

    
2268
# session
2269
session		required	pam_permit.so
2270

    
2271
# password
2272
password	required	pam_unix.so		no_warn try_first_pass
2273

    
2274
EOD;
2275

    
2276
	$pam_system =<<<EOD
2277
# auth
2278
auth		required	pam_unix.so		no_warn try_first_pass
2279

    
2280
# account
2281
account		required	pam_login_access.so
2282
account		required	pam_unix.so
2283

    
2284
# session
2285
session		required	pam_lastlog.so		no_fail
2286

    
2287
# password
2288
password	required	pam_unix.so		no_warn try_first_pass
2289

    
2290
EOD;
2291

    
2292
	$nsswitch =<<<EOD
2293
group: files
2294
hosts: files dns
2295
netgroup: files
2296
networks: files
2297
passwd: files
2298
shells: files
2299
services: files
2300
protocols: files
2301
rpc: files
2302

    
2303
EOD;
2304

    
2305
	if (isset($config['system']['webgui']['shellauth'])) {
2306
		if (($authcfg['type'] == "radius") && isset($authcfg['radius_auth_port'])) {
2307
			$radius_conf = "auth {$authcfg['host']}:{$authcfg['radius_auth_port']} " .
2308
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2309
			if (isset($authcfg['radius_acct_port'])) {
2310
				$radius_conf .= "acct {$authcfg['host']}:{$authcfg['radius_acct_port']} " .
2311
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2312
			}
2313
			
2314
			$pam_sshd =<<<EOD
2315
# auth
2316
auth            sufficient      pam_radius.so
2317
auth		required	pam_unix.so		no_warn try_first_pass
2318

    
2319
# account
2320
account		required	pam_nologin.so
2321
account		required	pam_login_access.so
2322
account         sufficient      pam_radius.so
2323

    
2324
# session
2325
session		required	pam_permit.so
2326

    
2327
# password
2328
password        sufficient      pam_radius.so
2329
password	required	pam_unix.so		no_warn try_first_pass
2330

    
2331
EOD;
2332

    
2333
			$pam_system =<<<EOD
2334
# auth
2335
auth            sufficient      pam_radius.so
2336
auth		required	pam_unix.so		no_warn try_first_pass
2337

    
2338
# account
2339
account		required	pam_login_access.so
2340
account         sufficient      pam_radius.so
2341

    
2342
# session
2343
session		required	pam_lastlog.so		no_fail
2344

    
2345
# password
2346
password        sufficient      pam_radius.so
2347
password	required	pam_unix.so		no_warn try_first_pass
2348

    
2349
EOD;
2350

    
2351
			@file_put_contents("/etc/radius.conf", $header . $radius_conf);
2352
		} elseif (($authcfg['type'] == "ldap") && !empty($authcfg['ldap_pam_groupdn'])) {
2353
			// do not try to reconnect
2354
			$ldapconf = "bind_policy soft\n";
2355
			// Bind/connect timelimit
2356
			$ldapconf .= "bind_timelimit {$authcfg['ldap_timeout']}\n";
2357
			$uri = ($authcfg['ldap_urltype'] == 'SSL/TLS Encrypted') ? 'ldaps' : 'ldap';
2358
			$ldapconf .= "uri {$uri}://{$authcfg['host']}/\n";
2359
			$ldapconf .= "port {$authcfg['ldap_port']}\n";
2360
			if ($authcfg['ldap_urltype'] == 'STARTTLS Encrypted')  {
2361
				$ldapconf .= "ssl start_tls\n";
2362
			} elseif ($authcfg['ldap_urltype'] == 'SSL/TLS Encrypted')  {
2363
				$ldapconf .= "ssl on\n";
2364
			}
2365
			if ($authcfg['ldap_urltype'] != 'Standard TCP') {
2366
				if ($authcfg['ldap_caref'] == 'global') {
2367
					$ldapconf .= "tls_cacertfile /etc/ssl/cert.pem\n";
2368
				} else {
2369
					$ca = array();
2370
					$ldappamcafile = "/var/etc/pam_ldap_ca.crt";
2371
					$ca['caref'] = $authcfg['ldap_caref'];
2372
					$cacrt = ca_chain($ca);
2373
					@file_put_contents($ldappamcafile, $cacrt); 
2374
					$ldapconf .= "tls_cacertfile {$ldappamcafile}\n";
2375
				}
2376
				$ldapconf .= "tls_checkpeer yes\n";
2377
			}
2378
			$ldapconf .= "ldap_version {$authcfg['ldap_protver']}\n";
2379
			$ldapconf .= "timelimit {$authcfg['ldap_timeout']}\n";
2380
			$ldapconf .= "base {$authcfg['ldap_basedn']}\n";
2381
			$scope = ($authcfg['ldap_scope' == 'one']) ? 'one' : 'sub';
2382
			$ldapconf .= "scope {$scope}\n";
2383
			$ldapconf .= "binddn {$authcfg['ldap_binddn']}\n";
2384
			$ldapconf .= "bindpw {$authcfg['ldap_bindpw']}\n";
2385
			$ldapconf .= "pam_login_attribute {$authcfg['ldap_attr_user']}\n";
2386
			$ldapconf .= "pam_member_attribute {$authcfg['ldap_attr_member']}\n";
2387
			//$ldapconf .= "pam_filter objectclass={$authcfg['ldap_attr_user']}\n";
2388
			$ldapconf .= "pam_groupdn {$authcfg['ldap_pam_groupdn']}\n";
2389
			//$ldapconf .= "pam_password ad\n";
2390

    
2391
			$pam_sshd =<<<EOD
2392
# auth
2393
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2394
auth		required	pam_unix.so		no_warn try_first_pass
2395

    
2396
# account
2397
account		required	pam_nologin.so
2398
account		required	pam_login_access.so
2399
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2400

    
2401
# session
2402
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2403
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2404
session		required	pam_permit.so
2405

    
2406
# password
2407
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2408
password	required	pam_unix.so		no_warn try_first_pass
2409

    
2410
EOD;
2411

    
2412
			$pam_system =<<<EOD
2413
# auth
2414
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2415
auth		required	pam_unix.so		no_warn try_first_pass
2416

    
2417
# account
2418
account		required	pam_login_access.so
2419
account         sufficient      pam_radius.so
2420
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2421

    
2422
# session
2423
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2424
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2425
session		required	pam_lastlog.so		no_fail
2426

    
2427
# password
2428
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2429
password	required	pam_unix.so		no_warn try_first_pass
2430

    
2431
EOD;
2432

    
2433
			$nsswitch =<<<EOD
2434
group: files ldap
2435
hosts: files dns
2436
netgroup: files
2437
networks: files
2438
passwd: files ldap
2439
shells: files
2440
services: files
2441
protocols: files
2442
rpc: files
2443

    
2444
EOD;
2445

    
2446
			@file_put_contents("/var/etc/pam_ldap.conf", $ldapconf);
2447
			@chmod("/var/etc/pam_ldap.conf", 0600);
2448
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2449
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2450
		}
2451
	}
2452

    
2453
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2454
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2455
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2456
}
2457
?>
(2-2/61)