Project

General

Profile

Download (72.8 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
	$keephistory = "{$user_home}/.keephistory";
785
	if (isset($user['keephistory']) && $shell_access &&
786
	    !file_exists($keephistory)) {
787
		@touch($keephistory);
788
		@chown($keephistory, $user_name);
789
	} elseif (!isset($user['keephistory'])) {
790
		unlink_if_exists($keephistory);
791
	} elseif (file_exists($keephistory) && (fileowner($keephistory) != $user['uid'])) {
792
		@chown($keephistory, $user_name);
793
	}
794

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

    
798
}
799

    
800
function local_user_del($user) {
801
	global $debug;
802

    
803
	/* remove all memberships */
804
	local_user_set_groups($user);
805

    
806
	/* Don't remove /root */
807
	if ($user['uid'] != 0) {
808
		$rmhome = "-r";
809
	}
810

    
811
	/* read from pw db */
812
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
813
	$pwread = fgets($fd);
814
	pclose($fd);
815
	$userattrs = explode(":", trim($pwread));
816

    
817
	if ($userattrs[0] != $user['name']) {
818
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
819
		return;
820
	}
821

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

    
825
	if ($debug) {
826
		log_error(sprintf(gettext("Running: %s"), $cmd));
827
	}
828
	mwexec($cmd);
829

    
830
	/* Delete user from groups needs a call to write_config() */
831
	local_group_del_user($user);
832
}
833

    
834
function local_user_set_password(&$user, $password) {
835
	global $config;
836

    
837
	unset($user['password']);
838
	unset($user['md5-hash']);
839
	unset($user['sha512-hash']);
840
	unset($user['bcrypt-hash']);
841

    
842
	/* Default to bcrypt hashing if unset.
843
	 * See https://redmine.pfsense.org/issues/12855
844
	 */
845
	$hashalgo = isset($config['system']['webgui']['pwhash']) ? $config['system']['webgui']['pwhash'] : 'bcrypt';
846

    
847
	switch ($hashalgo) {
848
		case 'sha512':
849
			$salt = substr(bin2hex(random_bytes(16)),0,16);
850
			$user['sha512-hash'] = crypt($password, '$6$'. $salt . '$');
851
			break;
852
		case 'bcrypt':
853
		default:
854
			$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
855
			break;
856
	}
857

    
858
	if (($user['name'] == $config['hasync']['username']) &&
859
	    ($config['hasync']['adminsync'] == 'on')) {
860
		$config['hasync']['new_password'] = $password;
861
	}
862
}
863

    
864
function local_user_get_groups($user, $all = false) {
865
	global $debug, $config;
866

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

    
872
	foreach ($config['system']['group'] as $group) {
873
		if ($all || (!$all && ($group['name'] != "all"))) {
874
			if (is_array($group['member'])) {
875
				if (in_array($user['uid'], $group['member'])) {
876
					$groups[] = $group['name'];
877
				}
878
			}
879
		}
880
	}
881

    
882
	if ($all) {
883
		$groups[] = "all";
884
	}
885

    
886
	sort($groups);
887

    
888
	return $groups;
889

    
890
}
891

    
892
function local_user_set_groups($user, $new_groups = NULL) {
893
	global $debug, $config, $groupindex, $userindex;
894

    
895
	if (!is_array($config['system']['group'])) {
896
		return;
897
	}
898

    
899
	$cur_groups = local_user_get_groups($user, true);
900
	$mod_groups = array();
901

    
902
	if (!is_array($new_groups)) {
903
		$new_groups = array();
904
	}
905

    
906
	if (!is_array($cur_groups)) {
907
		$cur_groups = array();
908
	}
909

    
910
	/* determine which memberships to add */
911
	foreach ($new_groups as $groupname) {
912
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
913
			continue;
914
		}
915
		$group = &$config['system']['group'][$groupindex[$groupname]];
916
		$group['member'][] = $user['uid'];
917
		$mod_groups[] = $group;
918

    
919
		/*
920
		 * If it's a new user, make sure it is added before try to
921
		 * add it as a member of a group
922
		 */
923
		if (!isset($userindex[$user['uid']])) {
924
			local_user_set($user);
925
		}
926
	}
927
	unset($group);
928

    
929
	/* determine which memberships to remove */
930
	foreach ($cur_groups as $groupname) {
931
		if (in_array($groupname, $new_groups)) {
932
			continue;
933
		}
934
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
935
			continue;
936
		}
937
		$group = &$config['system']['group'][$groupindex[$groupname]];
938
		if (is_array($group['member'])) {
939
			$index = array_search($user['uid'], $group['member']);
940
			array_splice($group['member'], $index, 1);
941
			$mod_groups[] = $group;
942
		}
943
	}
944
	unset($group);
945

    
946
	/* sync all modified groups */
947
	foreach ($mod_groups as $group) {
948
		local_group_set($group);
949
	}
950
}
951

    
952
function local_group_del_user($user) {
953
	global $config;
954

    
955
	if (!is_array($config['system']['group'])) {
956
		return;
957
	}
958

    
959
	foreach ($config['system']['group'] as $group) {
960
		if (is_array($group['member'])) {
961
			foreach ($group['member'] as $idx => $uid) {
962
				if ($user['uid'] == $uid) {
963
					unset($config['system']['group']['member'][$idx]);
964
				}
965
			}
966
		}
967
	}
968
}
969

    
970
function local_group_set($group, $reset = false) {
971
	global $debug;
972

    
973
	$group_name = $group['name'];
974
	$group_gid = $group['gid'];
975
	$group_members = '';
976

    
977
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
978
		$group_members = implode(",", $group['member']);
979
	}
980

    
981
	if (empty($group_name)) {
982
		return;
983
	}
984

    
985
	// If the group is now remote, make sure there is no local group with the same name
986
	if ($group['scope'] == "remote") {
987
		local_group_del($group);
988
		return;
989
	}
990

    
991
	/* determine add or mod */
992
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
993
		$group_op = "groupmod -l";
994
	} else {
995
		$group_op = "groupadd -n";
996
	}
997

    
998
	/* add or mod group db */
999
	$cmd = "/usr/sbin/pw {$group_op} " .
1000
		escapeshellarg($group_name) .
1001
		" -g " . escapeshellarg($group_gid) .
1002
		" -M " . escapeshellarg($group_members) . " 2>&1";
1003

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

    
1008
	mwexec($cmd);
1009
}
1010

    
1011
function local_group_del($group) {
1012
	global $debug;
1013

    
1014
	/* delete from group db */
1015
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
1016

    
1017
	if ($debug) {
1018
		log_error(sprintf(gettext("Running: %s"), $cmd));
1019
	}
1020
	mwexec($cmd);
1021
}
1022

    
1023
function ldap_test_connection($authcfg) {
1024
	if ($authcfg) {
1025
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1026
			$ldapproto = "ldaps";
1027
		} else {
1028
			$ldapproto = "ldap";
1029
		}
1030
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1031
		$ldapport = $authcfg['ldap_port'];
1032
		if (!empty($ldapport)) {
1033
			$ldapserver .= ":{$ldapport}";
1034
		}
1035
	} else {
1036
		return false;
1037
	}
1038

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

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

    
1050
	if ($error == true) {
1051
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
1052
		return false;
1053
	}
1054

    
1055
	/* Setup CA environment if needed. */
1056
	ldap_setup_caenv($ldap, $authcfg);
1057

    
1058
	return true;
1059
}
1060

    
1061
function ldap_setup_caenv($ldap, $authcfg) {
1062
	global $g;
1063
	require_once("certs.inc");
1064

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

    
1085
		$cert_path = "{$g['varrun_path']}/certs";
1086
		$cert_filename = "{$cert_path}/{$cert_details['hash']}.0";
1087
		safe_mkdir($cert_path);
1088
		unlink_if_exists($cert_filename);
1089
		file_put_contents($cert_filename, $cachain);
1090
		@chmod($cert_filename, 0600);
1091

    
1092
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1093
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, $cert_path);
1094
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, $cert_filename);
1095
	}
1096
}
1097

    
1098
function ldap_test_bind($authcfg) {
1099
	global $debug, $config, $g;
1100

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

    
1126
	/* first check if there is even an LDAP server populated */
1127
	if (!$ldapserver) {
1128
		return false;
1129
	}
1130

    
1131
	/* connect and see if server is up */
1132
	$error = false;
1133
	if (!($ldap = ldap_connect($ldapserver))) {
1134
		$error = true;
1135
	}
1136

    
1137
	if ($error == true) {
1138
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1139
		return false;
1140
	}
1141

    
1142
	/* Setup CA environment if needed. */
1143
	ldap_setup_caenv($ldap, $authcfg);
1144

    
1145
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1146
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1147
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1148
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1149
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1150

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

    
1159
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1160
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1161
	if ($ldapanon == true) {
1162
		if (!($res = @ldap_bind($ldap))) {
1163
			@ldap_close($ldap);
1164
			return false;
1165
		}
1166
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1167
		@ldap_close($ldap);
1168
		return false;
1169
	}
1170

    
1171
	@ldap_unbind($ldap);
1172

    
1173
	return true;
1174
}
1175

    
1176
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1177
	global $debug, $config, $g;
1178

    
1179
	if (!function_exists("ldap_connect")) {
1180
		return;
1181
	}
1182

    
1183
	$ous = array();
1184

    
1185
	if ($authcfg) {
1186
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1187
			$ldapproto = "ldaps";
1188
		} else {
1189
			$ldapproto = "ldap";
1190
		}
1191
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1192
		$ldapport = $authcfg['ldap_port'];
1193
		if (!empty($ldapport)) {
1194
			$ldapserver .= ":{$ldapport}";
1195
		}
1196
		$ldapbasedn = $authcfg['ldap_basedn'];
1197
		$ldapbindun = $authcfg['ldap_binddn'];
1198
		$ldapbindpw = $authcfg['ldap_bindpw'];
1199
		$ldapver = $authcfg['ldap_protver'];
1200
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1201
			$ldapanon = true;
1202
		} else {
1203
			$ldapanon = false;
1204
		}
1205
		$ldapname = $authcfg['name'];
1206
		$ldapfallback = false;
1207
		$ldapscope = $authcfg['ldap_scope'];
1208
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1209
	} else {
1210
		return false;
1211
	}
1212

    
1213
	/* first check if there is even an LDAP server populated */
1214
	if (!$ldapserver) {
1215
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1216
		return $ous;
1217
	}
1218

    
1219
	/* connect and see if server is up */
1220
	$error = false;
1221
	if (!($ldap = ldap_connect($ldapserver))) {
1222
		$error = true;
1223
	}
1224

    
1225
	if ($error == true) {
1226
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1227
		return $ous;
1228
	}
1229

    
1230
	/* Setup CA environment if needed. */
1231
	ldap_setup_caenv($ldap, $authcfg);
1232

    
1233
	$ldapfilter = "(|(ou=*)(cn=Users))";
1234

    
1235
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1236
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1237
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1238
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1239
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1240

    
1241
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1242
		if (!(@ldap_start_tls($ldap))) {
1243
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1244
			@ldap_close($ldap);
1245
			return false;
1246
		}
1247
	}
1248

    
1249
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1250
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1251
	if ($ldapanon == true) {
1252
		if (!($res = @ldap_bind($ldap))) {
1253
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1254
			@ldap_close($ldap);
1255
			return $ous;
1256
		}
1257
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1258
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1259
		@ldap_close($ldap);
1260
		return $ous;
1261
	}
1262

    
1263
	if ($ldapscope == "one") {
1264
		$ldapfunc = "ldap_list";
1265
	} else {
1266
		$ldapfunc = "ldap_search";
1267
	}
1268

    
1269
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1270
	$info = @ldap_get_entries($ldap, $search);
1271

    
1272
	if (is_array($info)) {
1273
		foreach ($info as $inf) {
1274
			if (!$show_complete_ou) {
1275
				$inf_split = explode(",", $inf['dn']);
1276
				$ou = $inf_split[0];
1277
				$ou = str_replace("OU=", "", $ou);
1278
				$ou = str_replace("CN=", "", $ou);
1279
			} else {
1280
				if ($inf['dn']) {
1281
					$ou = $inf['dn'];
1282
				}
1283
			}
1284
			if ($ou) {
1285
				$ous[] = $ou;
1286
			}
1287
		}
1288
	}
1289

    
1290
	@ldap_unbind($ldap);
1291

    
1292
	return $ous;
1293
}
1294

    
1295
function ldap_get_groups($username, $authcfg) {
1296
	global $debug, $config;
1297

    
1298
	if (!function_exists("ldap_connect")) {
1299
		return array();
1300
	}
1301

    
1302
	if (!$username) {
1303
		return array();
1304
	}
1305

    
1306
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1307
		$username_split = explode("@", $username);
1308
		$username = $username_split[0];
1309
	}
1310

    
1311
	if (stristr($username, "\\")) {
1312
		$username_split = explode("\\", $username);
1313
		$username = $username_split[0];
1314
	}
1315

    
1316
	//log_error("Getting LDAP groups for {$username}.");
1317
	if ($authcfg) {
1318
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1319
			$ldapproto = "ldaps";
1320
		} else {
1321
			$ldapproto = "ldap";
1322
		}
1323
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1324
		$ldapport = $authcfg['ldap_port'];
1325
		if (!empty($ldapport)) {
1326
			$ldapserver .= ":{$ldapport}";
1327
		}
1328
		$ldapbasedn = $authcfg['ldap_basedn'];
1329
		$ldapbindun = $authcfg['ldap_binddn'];
1330
		$ldapbindpw = $authcfg['ldap_bindpw'];
1331
		$ldapauthcont = $authcfg['ldap_authcn'];
1332
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1333
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1334
		$ldaptype = "";
1335
		$ldapver = $authcfg['ldap_protver'];
1336
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1337
			$ldapanon = true;
1338
		} else {
1339
			$ldapanon = false;
1340
		}
1341
		$ldapname = $authcfg['name'];
1342
		$ldapfallback = false;
1343
		$ldapscope = $authcfg['ldap_scope'];
1344
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1345
	} else {
1346
		return array();
1347
	}
1348

    
1349
	if (isset($authcfg['ldap_rfc2307'])) {
1350
		$ldapdn = $ldapbasedn;
1351
	} else {
1352
		$ldapdn = $_SESSION['ldapdn'];
1353
	}
1354

    
1355
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1356
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1357
	$memberof = array();
1358

    
1359
	/* connect and see if server is up */
1360
	$error = false;
1361
	if (!($ldap = ldap_connect($ldapserver))) {
1362
		$error = true;
1363
	}
1364

    
1365
	if ($error == true) {
1366
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1367
		return $memberof;
1368
	}
1369

    
1370
	/* Setup CA environment if needed. */
1371
	ldap_setup_caenv($ldap, $authcfg);
1372

    
1373
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1374
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1375
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1376
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1377
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1378

    
1379
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1380
		if (!(@ldap_start_tls($ldap))) {
1381
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1382
			@ldap_close($ldap);
1383
			return array();
1384
		}
1385
	}
1386

    
1387
	/* bind as user that has rights to read group attributes */
1388
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1389
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1390
	if ($ldapanon == true) {
1391
		if (!($res = @ldap_bind($ldap))) {
1392
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1393
			@ldap_close($ldap);
1394
			return array();
1395
		}
1396
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1397
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1398
		@ldap_close($ldap);
1399
		return $memberof;
1400
	}
1401

    
1402
	/* get groups from DN found */
1403
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1404
	/* since we know the DN is in $_SESSION['ldapdn'] */
1405
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1406
	if ($ldapscope == "one") {
1407
		$ldapfunc = "ldap_list";
1408
	} else {
1409
		$ldapfunc = "ldap_search";
1410
	}
1411

    
1412
	if (isset($authcfg['ldap_rfc2307'])) {
1413
		if (isset($authcfg['ldap_rfc2307_userdn'])) {
1414
			$ldac_splits = explode(";", $ldapauthcont);
1415
			foreach ($ldac_splits as $i => $ldac_split) {
1416
				$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1417
				$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1418
				$ldapfilter = "({$ldapnameattribute}={$username})";
1419
				if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1420
					$ldapdn = $ldac_split;
1421
				} else {
1422
					$ldapdn = $ldapsearchbasedn;
1423
				}
1424
				$usersearch = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1425
				$userinfo = @ldap_get_entries($ldap, $usersearch);
1426
			}
1427
			$username = $userinfo[0]['dn'];
1428
		}
1429
		$ldapfilter = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1430
	} else {
1431
		$ldapfilter = "({$ldapnameattribute}={$username})";
1432
	}
1433

    
1434
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1435
	$info = @ldap_get_entries($ldap, $search);
1436

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

    
1439
	if (is_array($gresults)) {
1440
		/* Iterate through the groups and throw them into an array */
1441
		foreach ($gresults as $grp) {
1442
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1443
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1444
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1445
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1446
			}
1447
		}
1448
	}
1449

    
1450
	/* Time to close LDAP connection */
1451
	@ldap_unbind($ldap);
1452

    
1453
	$groups = print_r($memberof, true);
1454

    
1455
	//log_error("Returning groups ".$groups." for user $username");
1456

    
1457
	return $memberof;
1458
}
1459

    
1460
function ldap_format_host($host) {
1461
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1462
}
1463

    
1464
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1465
	global $debug, $config;
1466

    
1467
	if (!$username) {
1468
		$attributes['error_message'] = gettext("Invalid Login.");
1469
		return false;
1470
	}
1471

    
1472
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1473
		$attributes['error_message'] = gettext("Invalid credentials.");
1474
		return false;
1475
	}
1476

    
1477
	if (!function_exists("ldap_connect")) {
1478
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1479
		$attributes['error_message'] = gettext("Internal error during authentication.");
1480
		return null;
1481
	}
1482

    
1483
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1484
		$username_split = explode("@", $username);
1485
		$username = $username_split[0];
1486
	}
1487
	if (stristr($username, "\\")) {
1488
		$username_split = explode("\\", $username);
1489
		$username = $username_split[0];
1490
	}
1491

    
1492
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1493

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

    
1538
	/* first check if there is even an LDAP server populated */
1539
	if (!$ldapserver) {
1540
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1541
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1542
		return null;
1543
	}
1544

    
1545
	/* Make sure we can connect to LDAP */
1546
	$error = false;
1547
	if (!($ldap = ldap_connect($ldapserver))) {
1548
		$error = true;
1549
	}
1550

    
1551
	/* Setup CA environment if needed. */
1552
	ldap_setup_caenv($ldap, $authcfg);
1553

    
1554
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1555
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1556
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1557
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1558
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1559

    
1560
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1561
		if (!(@ldap_start_tls($ldap))) {
1562
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1563
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1564
			@ldap_close($ldap);
1565
			return null;
1566
		}
1567
	}
1568

    
1569
	if ($error == true) {
1570
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1571
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1572
		return null;
1573
	}
1574

    
1575
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1576
	$error = false;
1577
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1578
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1579
	if ($ldapanon == true) {
1580
		if (!($res = @ldap_bind($ldap))) {
1581
			$error = true;
1582
		}
1583
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1584
		$error = true;
1585
	}
1586

    
1587
	if ($error == true) {
1588
		@ldap_close($ldap);
1589
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1590
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1591
		return null;
1592
	}
1593

    
1594
	/* Get LDAP Authcontainers and split em up. */
1595
	$ldac_splits = explode(";", $ldapauthcont);
1596

    
1597
	/* setup the usercount so we think we haven't found anyone yet */
1598
	$usercount = 0;
1599

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

    
1644
		if (isset($ldapgroupfilter) && !$groupsearch) {
1645
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1646
			continue;
1647
		}
1648
		if (isset($groupsearch)) {
1649
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1650
			if ($debug) {
1651
				log_auth(sprintf(gettext("LDAP group search: %s results."), $validgroup));
1652
			}
1653
		}
1654
		$info = ldap_get_entries($ldap, $search);
1655
		$matches = $info['count'];
1656
		if ($matches == 1) {
1657
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1658
			$_SESSION['ldapou'] = $ldac_split[$i];
1659
			$_SESSION['ldapon'] = "true";
1660
			$usercount = 1;
1661
			break;
1662
		}
1663
	}
1664

    
1665
	if ($usercount != 1) {
1666
		@ldap_unbind($ldap);
1667
		if ($debug) {
1668
			if ($usercount === 0) {
1669
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1670
			} else {
1671
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1672
			}
1673
		}
1674
		$attributes['error_message'] = gettext("Invalid login specified.");
1675
		return false;
1676
	}
1677

    
1678
	/* Now lets bind as the user we found */
1679
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1680
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1681
		if ($debug) {
1682
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1683
		}
1684
		@ldap_unbind($ldap);
1685
		return false;
1686
	}
1687

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

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

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

    
1700
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1701
		return false;
1702
	}
1703

    
1704
	return true;
1705
}
1706

    
1707
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1708
	global $debug, $config;
1709
	$ret = false;
1710

    
1711
	require_once("Auth/RADIUS.php");
1712
	require_once("Crypt/CHAP.php");
1713

    
1714
	if ($authcfg) {
1715
		$radiusservers = array();
1716
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1717
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1718
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1719
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1720
		if(isset($authcfg['radius_protocol'])) {
1721
			$radius_protocol = $authcfg['radius_protocol'];
1722
		} else {
1723
			$radius_protocol = 'PAP';
1724
		}
1725
	} else {
1726
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1727
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1728
		return null;
1729
	}
1730

    
1731
	// Create our instance
1732
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1733
	$rauth = new $classname($username, $password);
1734

    
1735
	/* Add new servers to our instance */
1736
	foreach ($radiusservers as $radsrv) {
1737
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1738
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1739
	}
1740

    
1741
	// Construct data package
1742
	$rauth->username = $username;
1743
	switch ($radius_protocol) {
1744
		case 'CHAP_MD5':
1745
		case 'MSCHAPv1':
1746
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1747
			$crpt = new $classname;
1748
			$crpt->username = $username;
1749
			$crpt->password = $password;
1750
			$rauth->challenge = $crpt->challenge;
1751
			$rauth->chapid = $crpt->chapid;
1752
			$rauth->response = $crpt->challengeResponse();
1753
			$rauth->flags = 1;
1754
			break;
1755

    
1756
		case 'MSCHAPv2':
1757
			$crpt = new Crypt_CHAP_MSv2;
1758
			$crpt->username = $username;
1759
			$crpt->password = $password;
1760
			$rauth->challenge = $crpt->authChallenge;
1761
			$rauth->peerChallenge = $crpt->peerChallenge;
1762
			$rauth->chapid = $crpt->chapid;
1763
			$rauth->response = $crpt->challengeResponse();
1764
			break;
1765

    
1766
		default:
1767
			$rauth->password = $password;
1768
			break;
1769
	}
1770

    
1771
	if (PEAR::isError($rauth->start())) {
1772
		$ret = null;
1773
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1774
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1775
	} else {
1776
		$nasid = $attributes['nas_identifier'];
1777
		$nasip = $authcfg['radius_nasip_attribute'];
1778
		if (empty($nasid)) {
1779
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1780
		}
1781
		if (!is_ipaddr($nasip)) {
1782
			$nasip = get_interface_ip($nasip);
1783

    
1784
			if (!is_ipaddr($nasip)) {
1785
				/* use first interface with IP as fallback for NAS-IP-Address
1786
				 * see https://redmine.pfsense.org/issues/11109 */
1787
				foreach (get_configured_interface_list() as $if) {
1788
					$nasip = get_interface_ip($if);
1789
					if (is_ipaddr($nasip)) {
1790
						break;
1791
					}
1792
				}
1793
			}
1794
		}
1795
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1796

    
1797
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1798
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1799

    
1800
		if(!empty($attributes['calling_station_id'])) {
1801
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1802
		}
1803
		// Carefully check that interface has a MAC address
1804
		if(!empty($nasmac)) {
1805
			$nasmac = mac_format($nasmac);
1806
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1807
		}
1808
		if(!empty($attributes['nas_port_type'])) {
1809
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1810
		}
1811
		if(!empty($attributes['nas_port'])) {
1812
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1813
		}
1814
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1815
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1816
		}
1817
	}
1818

    
1819
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1820

    
1821
	/* Send request */
1822
	$result = $rauth->send();
1823
	if (PEAR::isError($result)) {
1824
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1825
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1826
		$ret = null;
1827
	} else if ($result === true) {
1828
		$ret = true;
1829
	} else {
1830
		$ret = false;
1831
	}
1832

    
1833

    
1834
	// Get attributes, even if auth failed.
1835
	if ($rauth->getAttributes()) {
1836
	$attributes = array_merge($attributes,$rauth->listAttributes());
1837

    
1838
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1839
	if (!empty($attributes['session_terminate_time'])) {
1840
			$stt = &$attributes['session_terminate_time'];
1841
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1842
		}
1843
	}
1844

    
1845
	// close OO RADIUS_AUTHENTICATION
1846
	$rauth->close();
1847

    
1848
	return $ret;
1849
}
1850

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

    
1866
		foreach ($groups as & $grp) {
1867
			$grp = trim($grp);
1868
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1869
				$grp = substr($grp, 3);
1870
			}
1871
		}
1872
	}
1873
	return $groups;
1874
}
1875

    
1876
function get_user_expiration_date($username) {
1877
	$user = getUserEntry($username);
1878
	if ($user['expires']) {
1879
		return $user['expires'];
1880
	}
1881
}
1882

    
1883
function is_account_expired($username) {
1884
	$expirydate = get_user_expiration_date($username);
1885
	if ($expirydate) {
1886
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1887
			return true;
1888
		}
1889
	}
1890

    
1891
	return false;
1892
}
1893

    
1894
function is_account_disabled($username) {
1895
	$user = getUserEntry($username);
1896
	if (isset($user['disabled'])) {
1897
		return true;
1898
	}
1899

    
1900
	return false;
1901
}
1902

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

    
1949
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1950
		$settings['webgui']['dashboardcolumns'] = 2;
1951
	}
1952

    
1953
	return $settings;
1954
}
1955

    
1956
function save_widget_settings($username, $settings, $message = "") {
1957
	global $config, $userindex;
1958
	$user = getUserEntry($username);
1959

    
1960
	if (strlen($message) > 0) {
1961
		$msgout = $message;
1962
	} else {
1963
		$msgout = gettext("Widget configuration has been changed.");
1964
	}
1965

    
1966
	if (isset($user['customsettings'])) {
1967
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1968
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1969
	} else {
1970
		$config['widgets'] = $settings;
1971
		write_config($msgout);
1972
	}
1973
}
1974

    
1975
function auth_get_authserver($name) {
1976
	global $config;
1977

    
1978
	if (is_array($config['system']['authserver'])) {
1979
		foreach ($config['system']['authserver'] as $authcfg) {
1980
			if ($authcfg['name'] == $name) {
1981
				return $authcfg;
1982
			}
1983
		}
1984
	}
1985
	if ($name == "Local Database") {
1986
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1987
	}
1988
}
1989

    
1990
function auth_get_authserver_list() {
1991
	global $config;
1992

    
1993
	$list = array();
1994

    
1995
	if (is_array($config['system']['authserver'])) {
1996
		foreach ($config['system']['authserver'] as $authcfg) {
1997
			/* Add support for disabled entries? */
1998
			$list[$authcfg['name']] = $authcfg;
1999
		}
2000
	}
2001

    
2002
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
2003
	return $list;
2004
}
2005

    
2006
function getUserGroups($username, $authcfg, &$attributes = array()) {
2007
	global $config;
2008

    
2009
	$allowed_groups = array();
2010

    
2011
	switch ($authcfg['type']) {
2012
		case 'ldap':
2013
			$allowed_groups = @ldap_get_groups($username, $authcfg);
2014
			break;
2015
		case 'radius':
2016
			$allowed_groups = @radius_get_groups($attributes);
2017
			break;
2018
		default:
2019
			$user = getUserEntry($username);
2020
			$allowed_groups = @local_user_get_groups($user, true);
2021
			break;
2022
	}
2023

    
2024
	$member_groups = array();
2025
	if (is_array($config['system']['group'])) {
2026
		foreach ($config['system']['group'] as $group) {
2027
			if (in_array($group['name'], $allowed_groups)) {
2028
				$member_groups[] = $group['name'];
2029
			}
2030
		}
2031
	}
2032

    
2033
	return $member_groups;
2034
}
2035

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

    
2044
	if (is_array($username) || is_array($password)) {
2045
		return false;
2046
	}
2047

    
2048
	if (!$authcfg) {
2049
		return local_backed($username, $password, $attributes);
2050
	}
2051

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

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

    
2080
	return $authenticated;
2081
}
2082

    
2083
function session_auth() {
2084
	global $config, $_SESSION, $page;
2085

    
2086
	// Handle HTTPS httponly and secure flags
2087
	$currentCookieParams = session_get_cookie_params();
2088
	session_set_cookie_params(
2089
		$currentCookieParams["lifetime"],
2090
		$currentCookieParams["path"],
2091
		NULL,
2092
		($config['system']['webgui']['protocol'] == "https"),
2093
		true
2094
	);
2095

    
2096
	phpsession_begin();
2097

    
2098
	// Detect protocol change
2099
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2100
		phpsession_end();
2101
		return false;
2102
	}
2103

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

    
2151
	/* Show login page if they aren't logged in */
2152
	if (empty($_SESSION['Logged_In'])) {
2153
		phpsession_end(true);
2154
		return false;
2155
	}
2156

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

    
2184
	/* user hit the logout button */
2185
	if (isset($_POST['logout'])) {
2186

    
2187
		if ($_SESSION['Logout']) {
2188
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2189
		} else {
2190
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2191
		}
2192

    
2193
		/* wipe out $_SESSION */
2194
		$_SESSION = array();
2195

    
2196
		if (isset($_COOKIE[session_name()])) {
2197
			setcookie(session_name(), '', time()-42000, '/');
2198
		}
2199

    
2200
		/* and destroy it */
2201
		phpsession_destroy();
2202

    
2203
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2204
		$scriptElms = count($scriptName);
2205
		$scriptName = $scriptName[$scriptElms-1];
2206

    
2207
		if (isAjax()) {
2208
			return false;
2209
		}
2210

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

    
2214
		return false;
2215
	}
2216

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

    
2226
	/*
2227
	 * Same to re-enable Ajax.
2228
	 */
2229
	if ($_REQUEST['enable_ajax']) {
2230
		unset($_SESSION['NO_AJAX']);
2231
	}
2232
	phpsession_end(true);
2233
	return true;
2234
}
2235

    
2236
function print_credit() {
2237
	global $g;
2238

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

    
2262
function set_pam_auth() {
2263
	global $config;
2264

    
2265
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2266

    
2267
	unlink_if_exists("/etc/radius.conf");
2268
	unlink_if_exists("/var/etc/pam_ldap.conf");
2269
	unlink_if_exists("/var/etc/pam_ldap_ca.crt");
2270

    
2271
	$header = "# This file is automatically generated. Do not edit.\n\n";
2272
	$pam_sshd =<<<EOD
2273
# auth
2274
auth		required	pam_unix.so		no_warn try_first_pass
2275

    
2276
# account
2277
account		required	pam_nologin.so
2278
account		required	pam_login_access.so
2279
account		required	pam_unix.so
2280

    
2281
# session
2282
session		required	pam_permit.so
2283

    
2284
# password
2285
password	required	pam_unix.so		no_warn try_first_pass
2286

    
2287
EOD;
2288

    
2289
	$pam_system =<<<EOD
2290
# auth
2291
auth		required	pam_unix.so		no_warn try_first_pass
2292

    
2293
# account
2294
account		required	pam_login_access.so
2295
account		required	pam_unix.so
2296

    
2297
# session
2298
session		required	pam_lastlog.so		no_fail
2299

    
2300
# password
2301
password	required	pam_unix.so		no_warn try_first_pass
2302

    
2303
EOD;
2304

    
2305
	$nsswitch =<<<EOD
2306
group: files
2307
hosts: files dns
2308
netgroup: files
2309
networks: files
2310
passwd: files
2311
shells: files
2312
services: files
2313
protocols: files
2314
rpc: files
2315

    
2316
EOD;
2317

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

    
2332
# account
2333
account		required	pam_nologin.so
2334
account		required	pam_login_access.so
2335
account         sufficient      pam_radius.so
2336

    
2337
# session
2338
session		required	pam_permit.so
2339

    
2340
# password
2341
password        sufficient      pam_radius.so
2342
password	required	pam_unix.so		no_warn try_first_pass
2343

    
2344
EOD;
2345

    
2346
			$pam_system =<<<EOD
2347
# auth
2348
auth            sufficient      pam_radius.so
2349
auth		required	pam_unix.so		no_warn try_first_pass
2350

    
2351
# account
2352
account		required	pam_login_access.so
2353
account         sufficient      pam_radius.so
2354

    
2355
# session
2356
session		required	pam_lastlog.so		no_fail
2357

    
2358
# password
2359
password        sufficient      pam_radius.so
2360
password	required	pam_unix.so		no_warn try_first_pass
2361

    
2362
EOD;
2363

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

    
2404
			$pam_sshd =<<<EOD
2405
# auth
2406
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2407
auth		required	pam_unix.so		no_warn try_first_pass
2408

    
2409
# account
2410
account		required	pam_nologin.so
2411
account		required	pam_login_access.so
2412
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2413

    
2414
# session
2415
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2416
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2417
session		required	pam_permit.so
2418

    
2419
# password
2420
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2421
password	required	pam_unix.so		no_warn try_first_pass
2422

    
2423
EOD;
2424

    
2425
			$pam_system =<<<EOD
2426
# auth
2427
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2428
auth		required	pam_unix.so		no_warn try_first_pass
2429

    
2430
# account
2431
account		required	pam_login_access.so
2432
account         sufficient      pam_radius.so
2433
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2434

    
2435
# session
2436
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2437
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2438
session		required	pam_lastlog.so		no_fail
2439

    
2440
# password
2441
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2442
password	required	pam_unix.so		no_warn try_first_pass
2443

    
2444
EOD;
2445

    
2446
			$nsswitch =<<<EOD
2447
group: files ldap
2448
hosts: files dns
2449
netgroup: files
2450
networks: files
2451
passwd: files ldap
2452
shells: files
2453
services: files
2454
protocols: files
2455
rpc: files
2456

    
2457
EOD;
2458

    
2459
			@file_put_contents("/var/etc/pam_ldap.conf", $ldapconf);
2460
			@chmod("/var/etc/pam_ldap.conf", 0600);
2461
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2462
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2463
		}
2464
	}
2465

    
2466
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2467
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2468
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2469
}
2470
?>
(2-2/61)