Project

General

Profile

Download (72.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * auth.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>
7
 * Copyright (c) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 * Copyright (c) 2006 Paul Taylor <paultaylor@winn-dixie.com>
9
 * Copyright (c) 2004-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
		/* Don't remove /root */
486
		if ($user['uid'] != 0) {
487
			$rmhome = escapeshellarg('-r');
488
		} else {
489
			$rmhome = '';
490
		}
491

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

    
505
		$system_user = $config['system']['user'];
506
		for ($i = 0; $i < count($system_user); $i++) {
507
			if ($system_user[$i]['name'] == $user['name']) {
508
				log_error("Removing user: {$user['name']}");
509
				unset($config['system']['user'][$i]);
510
				break;
511
			}
512
		}
513
	}
514

    
515
	foreach($g2del as $group) {
516
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
517
			continue;
518
		}
519

    
520
		$cmd = "/usr/sbin/pw groupdel -g " .
521
		    escapeshellarg($group['name']);
522
		if ($debug) {
523
			log_error(sprintf(gettext("Running: %s"), $cmd));
524
		}
525
		mwexec($cmd);
526

    
527
		$system_group = $config['system']['group'];
528
		for ($i = 0; $i < count($system_group); $i++) {
529
			if ($system_group[$i]['name'] == $group['name']) {
530
				log_error("Removing group: {$group['name']}");
531
				unset($config['system']['group'][$i]);
532
				break;
533
			}
534
		}
535
	}
536

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

    
542
	foreach ($g2add as $group) {
543
		log_error("Adding group: {$group['name']}");
544
		$config['system']['group'][] = $group;
545
	}
546

    
547
	/* Sort it alphabetically */
548
	usort($config['system']['user'], function($a, $b) {
549
		return strcmp($a['name'], $b['name']);
550
	});
551
	usort($config['system']['group'], function($a, $b) {
552
		return strcmp($a['name'], $b['name']);
553
	});
554

    
555
	write_config("Sync'd users and groups via XMLRPC");
556

    
557
	/* make sure the all group exists */
558
	$allgrp = getGroupEntryByGID(1998);
559
	local_group_set($allgrp, true);
560

    
561
	foreach ($u2add as $user) {
562
		local_user_set($user);
563
	}
564

    
565
	foreach ($g2add as $group) {
566
		local_group_set($group);
567
	}
568
}
569

    
570
function local_reset_accounts() {
571
	global $debug, $config;
572

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

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

    
627
	/* make sure the all group exists */
628
	$allgrp = getGroupEntryByGID(1998);
629
	local_group_set($allgrp, true);
630

    
631
	/* sync all local users */
632
	if (is_array($config['system']['user'])) {
633
		foreach ($config['system']['user'] as $user) {
634
			local_user_set($user);
635
		}
636
	}
637

    
638
	/* sync all local groups */
639
	if (is_array($config['system']['group'])) {
640
		foreach ($config['system']['group'] as $group) {
641
			local_group_set($group);
642
		}
643
	}
644
}
645

    
646
function local_user_set(& $user) {
647
	global $g, $debug;
648

    
649
	if (empty($user['sha512-hash']) && empty($user['bcrypt-hash']) && empty($user['password'])) {
650
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
651
		return;
652
	}
653

    
654

    
655
	$home_base = "/home/";
656
	$user_uid = $user['uid'];
657
	$user_name = $user['name'];
658
	$user_home = "{$home_base}{$user_name}";
659
	$user_shell = "/etc/rc.initial";
660
	$user_group = "nobody";
661

    
662
	// Ensure $home_base exists and is writable
663
	if (!is_dir($home_base)) {
664
		mkdir($home_base, 0755);
665
	}
666

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

    
686
	/* Lock out disabled or expired users, unless it's root/admin. */
687
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
688
		$user_shell = "/sbin/nologin";
689
		$lock_account = true;
690
	}
691

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

    
713
	/* read from pw db */
714
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
715
	$pwread = fgets($fd);
716
	pclose($fd);
717
	$userattrs = explode(":", trim($pwread));
718

    
719
	$skel_dir = '/etc/skel';
720

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

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

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

    
752
	/* create user directory if required */
753
	if (!is_dir($user_home)) {
754
		mkdir($user_home, 0700);
755
	}
756
	@chown($user_home, $user_name);
757
	@chgrp($user_home, $user_group);
758

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

    
767
	/* write out ssh authorized key file */
768
	$sshdir = "{$user_home}/.ssh";
769
	if ($user['authorizedkeys']) {
770
		if (!is_dir("{$user_home}/.ssh")) {
771
			@mkdir($sshdir, 0700);
772
			@chown($sshdir, $user_name);
773
		} elseif (file_exists($sshdir) && (fileowner($sshdir) != $user['uid'])) {
774
			@chown($sshdir, $user_name);
775
			@chown("{$sshdir}/*", $user_name);
776
		}
777
		$keys = base64_decode($user['authorizedkeys']);
778
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
779
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
780
	} else {
781
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
782
	}
783

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

    
787
}
788

    
789
function local_user_del($user) {
790
	global $debug;
791

    
792
	/* remove all memberships */
793
	local_user_set_groups($user);
794

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

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

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

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

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

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

    
823
function local_user_set_password(&$user, $password) {
824
	global $config;
825

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

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

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

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

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

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

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

    
871
	if ($all) {
872
		$groups[] = "all";
873
	}
874

    
875
	sort($groups);
876

    
877
	return $groups;
878

    
879
}
880

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

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

    
888
	$cur_groups = local_user_get_groups($user, true);
889
	$mod_groups = array();
890

    
891
	if (!is_array($new_groups)) {
892
		$new_groups = array();
893
	}
894

    
895
	if (!is_array($cur_groups)) {
896
		$cur_groups = array();
897
	}
898

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

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

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

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

    
941
function local_group_del_user($user) {
942
	global $config;
943

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

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

    
959
function local_group_set($group, $reset = false) {
960
	global $debug;
961

    
962
	$group_name = $group['name'];
963
	$group_gid = $group['gid'];
964
	$group_members = '';
965

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

    
970
	if (empty($group_name)) {
971
		return;
972
	}
973

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

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

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

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

    
997
	mwexec($cmd);
998
}
999

    
1000
function local_group_del($group) {
1001
	global $debug;
1002

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

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

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

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

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

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

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

    
1047
	return true;
1048
}
1049

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

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

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

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

    
1087
function ldap_test_bind($authcfg) {
1088
	global $debug, $config, $g;
1089

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

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

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

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

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

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

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

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

    
1160
	@ldap_unbind($ldap);
1161

    
1162
	return true;
1163
}
1164

    
1165
function ldap_get_user_ous($show_complete_ou, $authcfg) {
1166
	global $debug, $config, $g;
1167

    
1168
	if (!function_exists("ldap_connect")) {
1169
		return;
1170
	}
1171

    
1172
	$ous = array();
1173

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

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

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

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

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

    
1222
	$ldapfilter = "(|(ou=*)(cn=Users))";
1223

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

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

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

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

    
1258
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1259
	$info = @ldap_get_entries($ldap, $search);
1260

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

    
1279
	@ldap_unbind($ldap);
1280

    
1281
	return $ous;
1282
}
1283

    
1284
function ldap_get_groups($username, $authcfg) {
1285
	global $debug, $config;
1286

    
1287
	if (!function_exists("ldap_connect")) {
1288
		return array();
1289
	}
1290

    
1291
	if (!$username) {
1292
		return array();
1293
	}
1294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1445
	return $memberof;
1446
}
1447

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1692
	return true;
1693
}
1694

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

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

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

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

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

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

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

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

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

    
1771
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1772
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1773

    
1774
		if(!empty($attributes['calling_station_id'])) {
1775
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1776
		}
1777
		// Carefully check that interface has a MAC address
1778
		if(!empty($nasmac)) {
1779
			$nasmac = mac_format($nasmac);
1780
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1781
		}
1782
		if(!empty($attributes['nas_port_type'])) {
1783
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1784
		}
1785
		if(!empty($attributes['nas_port'])) {
1786
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1787
		}
1788
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1789
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1790
		}
1791
	}
1792

    
1793
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1794

    
1795
	/* Send request */
1796
	$result = $rauth->send();
1797
	if (PEAR::isError($result)) {
1798
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1799
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1800
		$ret = null;
1801
	} else if ($result === true) {
1802
		$ret = true;
1803
	} else {
1804
		$ret = false;
1805
	}
1806

    
1807

    
1808
	// Get attributes, even if auth failed.
1809
	if ($rauth->getAttributes()) {
1810
	$attributes = array_merge($attributes,$rauth->listAttributes());
1811

    
1812
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1813
	if (!empty($attributes['session_terminate_time'])) {
1814
			$stt = &$attributes['session_terminate_time'];
1815
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1816
		}
1817
	}
1818

    
1819
	// close OO RADIUS_AUTHENTICATION
1820
	$rauth->close();
1821

    
1822
	return $ret;
1823
}
1824

    
1825
function nasip_fallback($ip) {
1826
	if (!is_ipaddr($ip)) {
1827
		$nasip = get_interface_ip($ip);
1828

    
1829
		if (!is_ipaddr($nasip)) {
1830
			/* use first interface with IP as fallback for NAS-IP-Address
1831
			 * see https://redmine.pfsense.org/issues/11109 */
1832
			foreach (get_configured_interface_list() as $if) {
1833
				$nasip = get_interface_ip($if);
1834
				if (is_ipaddr($nasip)) {
1835
					break;
1836
				}
1837
			}
1838
		}
1839
	} else {
1840
		$nasip = $ip;
1841
	}
1842

    
1843
	return $nasip;
1844
}
1845

    
1846
/*
1847
	$attributes must contain a "class" key containing the groups and local
1848
	groups must exist to match.
1849
*/
1850
function radius_get_groups($attributes) {
1851
	$groups = array();
1852
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1853
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1854
		$groups = array();
1855
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1856
			foreach ($attributes['class'] as $class) {
1857
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1858
			}
1859
		}
1860

    
1861
		foreach ($groups as & $grp) {
1862
			$grp = trim($grp);
1863
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1864
				$grp = substr($grp, 3);
1865
			}
1866
		}
1867
	}
1868
	return $groups;
1869
}
1870

    
1871
function get_user_expiration_date($username) {
1872
	$user = getUserEntry($username);
1873
	if ($user['expires']) {
1874
		return $user['expires'];
1875
	}
1876
}
1877

    
1878
function is_account_expired($username) {
1879
	$expirydate = get_user_expiration_date($username);
1880
	if ($expirydate) {
1881
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1882
			return true;
1883
		}
1884
	}
1885

    
1886
	return false;
1887
}
1888

    
1889
function is_account_disabled($username) {
1890
	$user = getUserEntry($username);
1891
	if (isset($user['disabled'])) {
1892
		return true;
1893
	}
1894

    
1895
	return false;
1896
}
1897

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

    
1944
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1945
		$settings['webgui']['dashboardcolumns'] = 2;
1946
	}
1947

    
1948
	return $settings;
1949
}
1950

    
1951
function save_widget_settings($username, $settings, $message = "") {
1952
	global $config, $userindex;
1953
	$user = getUserEntry($username);
1954

    
1955
	if (strlen($message) > 0) {
1956
		$msgout = $message;
1957
	} else {
1958
		$msgout = gettext("Widget configuration has been changed.");
1959
	}
1960

    
1961
	if (isset($user['customsettings'])) {
1962
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1963
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1964
	} else {
1965
		$config['widgets'] = $settings;
1966
		write_config($msgout);
1967
	}
1968
}
1969

    
1970
function auth_get_authserver($name) {
1971
	global $config;
1972

    
1973
	if (is_array($config['system']['authserver'])) {
1974
		foreach ($config['system']['authserver'] as $authcfg) {
1975
			if ($authcfg['name'] == $name) {
1976
				return $authcfg;
1977
			}
1978
		}
1979
	}
1980
	if ($name == "Local Database") {
1981
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1982
	}
1983
}
1984

    
1985
function auth_get_authserver_list() {
1986
	global $config;
1987

    
1988
	$list = array();
1989

    
1990
	if (is_array($config['system']['authserver'])) {
1991
		foreach ($config['system']['authserver'] as $authcfg) {
1992
			/* Add support for disabled entries? */
1993
			$list[$authcfg['name']] = $authcfg;
1994
		}
1995
	}
1996

    
1997
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1998
	return $list;
1999
}
2000

    
2001
function getUserGroups($username, $authcfg, &$attributes = array()) {
2002
	global $config;
2003

    
2004
	$allowed_groups = array();
2005

    
2006
	switch ($authcfg['type']) {
2007
		case 'ldap':
2008
			$allowed_groups = @ldap_get_groups($username, $authcfg);
2009
			break;
2010
		case 'radius':
2011
			$allowed_groups = @radius_get_groups($attributes);
2012
			break;
2013
		default:
2014
			$user = getUserEntry($username);
2015
			$allowed_groups = @local_user_get_groups($user, true);
2016
			break;
2017
	}
2018

    
2019
	$member_groups = array();
2020
	if (is_array($config['system']['group'])) {
2021
		foreach ($config['system']['group'] as $group) {
2022
			if (in_array($group['name'], $allowed_groups)) {
2023
				$member_groups[] = $group['name'];
2024
			}
2025
		}
2026
	}
2027

    
2028
	return $member_groups;
2029
}
2030

    
2031
/*
2032
Possible return values :
2033
true : authentication worked
2034
false : authentication failed (invalid login/password, not enough permission, etc...)
2035
null : error during authentication process (unable to reach remote server, etc...)
2036
*/
2037
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
2038

    
2039
	if (is_array($username) || is_array($password)) {
2040
		return false;
2041
	}
2042

    
2043
	if (!$authcfg) {
2044
		return local_backed($username, $password, $attributes);
2045
	}
2046

    
2047
	$authenticated = false;
2048
	switch ($authcfg['type']) {
2049
		case 'ldap':
2050
			try {
2051
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
2052
			} catch (Exception $e) {
2053
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
2054
			}
2055
			break;
2056

    
2057
			break;
2058
		case 'radius':
2059
			try {
2060
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
2061
			} catch (Exception $e) {
2062
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
2063
			}
2064
			break;
2065
		default:
2066
			/* lookup user object by name */
2067
			try {
2068
				$authenticated = local_backed($username, $password, $attributes);
2069
			} catch (Exception $e) {
2070
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
2071
			}
2072
			break;
2073
		}
2074

    
2075
	return $authenticated;
2076
}
2077

    
2078
function session_auth() {
2079
	global $config, $_SESSION, $page;
2080

    
2081
	// Handle HTTPS httponly and secure flags
2082
	$currentCookieParams = session_get_cookie_params();
2083
	session_set_cookie_params(
2084
		$currentCookieParams["lifetime"],
2085
		$currentCookieParams["path"],
2086
		NULL,
2087
		($config['system']['webgui']['protocol'] == "https"),
2088
		true
2089
	);
2090

    
2091
	phpsession_begin();
2092

    
2093
	// Detect protocol change
2094
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2095
		phpsession_end();
2096
		return false;
2097
	}
2098

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

    
2146
	/* Show login page if they aren't logged in */
2147
	if (empty($_SESSION['Logged_In'])) {
2148
		phpsession_end(true);
2149
		return false;
2150
	}
2151

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

    
2179
	/* user hit the logout button */
2180
	if (isset($_POST['logout'])) {
2181

    
2182
		if ($_SESSION['Logout']) {
2183
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2184
		} else {
2185
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2186
		}
2187

    
2188
		/* wipe out $_SESSION */
2189
		$_SESSION = array();
2190

    
2191
		if (isset($_COOKIE[session_name()])) {
2192
			setcookie(session_name(), '', time()-42000, '/');
2193
		}
2194

    
2195
		/* and destroy it */
2196
		phpsession_destroy();
2197

    
2198
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2199
		$scriptElms = count($scriptName);
2200
		$scriptName = $scriptName[$scriptElms-1];
2201

    
2202
		if (isAjax()) {
2203
			return false;
2204
		}
2205

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

    
2209
		return false;
2210
	}
2211

    
2212
	/*
2213
	 * this is for debugging purpose if you do not want to use Ajax
2214
	 * to submit a HTML form. It basically disables the observation
2215
	 * of the submit event and hence does not trigger Ajax.
2216
	 */
2217
	if ($_REQUEST['disable_ajax']) {
2218
		$_SESSION['NO_AJAX'] = "True";
2219
	}
2220

    
2221
	/*
2222
	 * Same to re-enable Ajax.
2223
	 */
2224
	if ($_REQUEST['enable_ajax']) {
2225
		unset($_SESSION['NO_AJAX']);
2226
	}
2227
	phpsession_end(true);
2228
	return true;
2229
}
2230

    
2231
function print_credit() {
2232
	global $g;
2233

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

    
2257
function set_pam_auth() {
2258
	global $config;
2259

    
2260
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2261

    
2262
	unlink_if_exists("/etc/radius.conf");
2263
	unlink_if_exists("/var/etc/pam_ldap.conf");
2264
	unlink_if_exists("/var/etc/pam_ldap_ca.crt");
2265

    
2266
	$header = "# This file is automatically generated. Do not edit.\n\n";
2267
	$pam_sshd =<<<EOD
2268
# auth
2269
auth		required	pam_unix.so		no_warn try_first_pass
2270

    
2271
# account
2272
account		required	pam_nologin.so
2273
account		required	pam_login_access.so
2274
account		required	pam_unix.so
2275

    
2276
# session
2277
session		required	pam_permit.so
2278

    
2279
# password
2280
password	required	pam_unix.so		no_warn try_first_pass
2281

    
2282
EOD;
2283

    
2284
	$pam_system =<<<EOD
2285
# auth
2286
auth		required	pam_unix.so		no_warn try_first_pass
2287

    
2288
# account
2289
account		required	pam_login_access.so
2290
account		required	pam_unix.so
2291

    
2292
# session
2293
session		required	pam_lastlog.so		no_fail
2294

    
2295
# password
2296
password	required	pam_unix.so		no_warn try_first_pass
2297

    
2298
EOD;
2299

    
2300
	$nsswitch =<<<EOD
2301
group: files
2302
hosts: files dns
2303
netgroup: files
2304
networks: files
2305
passwd: files
2306
shells: files
2307
services: files
2308
protocols: files
2309
rpc: files
2310

    
2311
EOD;
2312

    
2313
	if (isset($config['system']['webgui']['shellauth'])) {
2314
		if (($authcfg['type'] == "radius") && isset($authcfg['radius_auth_port'])) {
2315
			$radius_conf = "auth {$authcfg['host']}:{$authcfg['radius_auth_port']} " .
2316
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2317
			if (isset($authcfg['radius_acct_port'])) {
2318
				$radius_conf .= "acct {$authcfg['host']}:{$authcfg['radius_acct_port']} " .
2319
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2320
			}
2321
			
2322
			$pam_sshd =<<<EOD
2323
# auth
2324
auth            sufficient      pam_radius.so
2325
auth		required	pam_unix.so		no_warn try_first_pass
2326

    
2327
# account
2328
account		required	pam_nologin.so
2329
account		required	pam_login_access.so
2330
account         sufficient      pam_radius.so
2331

    
2332
# session
2333
session		required	pam_permit.so
2334

    
2335
# password
2336
password        sufficient      pam_radius.so
2337
password	required	pam_unix.so		no_warn try_first_pass
2338

    
2339
EOD;
2340

    
2341
			$pam_system =<<<EOD
2342
# auth
2343
auth            sufficient      pam_radius.so
2344
auth		required	pam_unix.so		no_warn try_first_pass
2345

    
2346
# account
2347
account		required	pam_login_access.so
2348
account         sufficient      pam_radius.so
2349

    
2350
# session
2351
session		required	pam_lastlog.so		no_fail
2352

    
2353
# password
2354
password        sufficient      pam_radius.so
2355
password	required	pam_unix.so		no_warn try_first_pass
2356

    
2357
EOD;
2358

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

    
2399
			$pam_sshd =<<<EOD
2400
# auth
2401
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2402
auth		required	pam_unix.so		no_warn try_first_pass
2403

    
2404
# account
2405
account		required	pam_nologin.so
2406
account		required	pam_login_access.so
2407
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2408

    
2409
# session
2410
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2411
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2412
session		required	pam_permit.so
2413

    
2414
# password
2415
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2416
password	required	pam_unix.so		no_warn try_first_pass
2417

    
2418
EOD;
2419

    
2420
			$pam_system =<<<EOD
2421
# auth
2422
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2423
auth		required	pam_unix.so		no_warn try_first_pass
2424

    
2425
# account
2426
account		required	pam_login_access.so
2427
account         sufficient      pam_radius.so
2428
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2429

    
2430
# session
2431
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2432
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2433
session		required	pam_lastlog.so		no_fail
2434

    
2435
# password
2436
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2437
password	required	pam_unix.so		no_warn try_first_pass
2438

    
2439
EOD;
2440

    
2441
			$nsswitch =<<<EOD
2442
group: files ldap
2443
hosts: files dns
2444
netgroup: files
2445
networks: files
2446
passwd: files ldap
2447
shells: files
2448
services: files
2449
protocols: files
2450
rpc: files
2451

    
2452
EOD;
2453

    
2454
			@file_put_contents("/var/etc/pam_ldap.conf", $ldapconf);
2455
			@chmod("/var/etc/pam_ldap.conf", 0600);
2456
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2457
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2458
		}
2459
	}
2460

    
2461
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2462
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2463
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2464
}
2465
?>
(3-3/62)