Project

General

Profile

Download (73.4 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-2024 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
require_once("config.lib.inc");
32
include_once('phpsessionmanager.inc');
33
if (!$do_not_include_config_gui_inc) {
34
	require_once("config.gui.inc");
35
}
36

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

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

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

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

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

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

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

    
104
	if (!$found_host) {
105
		foreach (config_get_path('dyndnses/dyndns', []) as $dyndns) {
106
			if (!is_array($dyndns) || empty($dyndns)) {
107
				continue;
108
			}
109
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
110
				$found_host = true;
111
				break;
112
			}
113
		}
114
	}
115

    
116
	if (!$found_host) {
117
		foreach (config_get_path('dnsupdates/dnsupdate', []) as $rfc2136) {
118
			if (!is_array($rfc2136) || empty($rfc2136)) {
119
				continue;
120
			}
121
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
122
				$found_host = true;
123
				break;
124
			}
125
		}
126
	}
127

    
128
	if (!$found_host) {
129
		$althosts = explode(" ", config_get_path('system/webgui/althostnames', ""));
130
		foreach ($althosts as $ah) {
131
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
132
				$found_host = true;
133
				break;
134
			}
135
		}
136
	}
137

    
138
	if ($found_host == false) {
139
		if (!security_checks_disabled()) {
140
			display_error_form("501", gettext("Potential DNS Rebind attack detected, see https://en.wikipedia.org/wiki/DNS_rebinding<br />Try accessing the router by IP address instead of by hostname."));
141
			exit;
142
		}
143
		$security_passed = false;
144
	}
145
}
146

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

    
184
			if (!$found_host) {
185
				$althosts = explode(" ", config_get_path('system/webgui/althostnames', ""));
186
				foreach ($althosts as $ah) {
187
					if (strcasecmp($referrer_host, $ah) == 0) {
188
						$found_host = true;
189
						break;
190
					}
191
				}
192
			}
193

    
194
			if (!$found_host) {
195
				foreach (config_get_path('dyndnses/dyndns', []) as $dyndns) {
196
					if (!is_array($dyndns) || empty($dyndns)) {
197
						continue;
198
					}
199
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
200
						$found_host = true;
201
						break;
202
					}
203
				}
204
			}
205

    
206
			if (!$found_host) {
207
				foreach (config_get_path('dnsupdates/dnsupdate', []) as $rfc2136) {
208
					if (!is_array($rfc2136) || empty($rfc2136)) {
209
						continue;
210
					}
211
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
212
						$found_host = true;
213
						break;
214
					}
215
				}
216
			}
217

    
218
			if (!$found_host) {
219
				$interface_list_ips = get_configured_ip_addresses();
220
				foreach ($interface_list_ips as $ilips) {
221
					if (strcasecmp($referrer_host, $ilips) == 0) {
222
						$found_host = true;
223
						break;
224
					}
225
				}
226
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
227
				foreach ($interface_list_ipv6s as $ilipv6s) {
228
					$ilipv6s = explode('%', $ilipv6s)[0];
229
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
230
						$found_host = true;
231
						break;
232
					}
233
				}
234
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
235
					// allow SSH port forwarded connections and links from localhost
236
					$found_host = true;
237
				}
238
			}
239

    
240
			/* Fall back to probing active interface addresses rather than config.xml to allow
241
			 * changed addresses that have not yet been applied.
242
			 * See https://redmine.pfsense.org/issues/8822
243
			 */
244
			if (!$found_host) {
245
				$refifs = get_interface_arr();
246
				foreach ($refifs as $rif) {
247
					if (($referrer_host == find_interface_ip($rif)) ||
248
					    ($referrer_host == find_interface_ipv6($rif)) ||
249
					    ($referrer_host == find_interface_ipv6_ll($rif))) {
250
						$found_host = true;
251
						break;
252
					}
253
				}
254
			}
255
		}
256
		if ($found_host == false) {
257
			if (!security_checks_disabled()) {
258
				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.");
259
				exit;
260
			}
261
			$security_passed = false;
262
		}
263
	} else {
264
		$security_passed = false;
265
	}
266
}
267

    
268
if (function_exists("display_error_form") && $security_passed) {
269
	/* Security checks passed, so it should be OK to turn them back on */
270
	restore_security_checks();
271
}
272
unset($security_passed);
273

    
274
$groupindex = index_groups();
275
$userindex = index_users();
276

    
277
function index_groups() {
278
	global $g, $debug, $groupindex;
279

    
280
	$groupindex = array();
281

    
282
	$i = 0;
283
	foreach (config_get_path('system/group', []) as $groupent) {
284
		$groupindex[$groupent['name']] = $i;
285
		$i++;
286
	}
287

    
288
	return ($groupindex);
289
}
290

    
291
function index_users() {
292
	$i = 0;
293
	foreach (config_get_path('system/user', []) as $userent) {
294
		$userindex[$userent['name']] = $i;
295
		$i++;
296
	}
297

    
298
	return ($userindex);
299
}
300

    
301
function & getUserEntry($name) {
302
	global $debug, $config, $userindex;
303
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
304

    
305
	if (isset($userindex[$name])) {
306
		return $config['system']['user'][$userindex[$name]];
307
	} elseif ($authcfg['type'] != "Local Database") {
308
		$user = array();
309
		$user['name'] = $name;
310
		return $user;
311
	}
312
}
313

    
314
function & getUserEntryByUID($uid) {
315
	global $debug, $config;
316

    
317
	if (!is_array(array_get_path($config, 'system/user'))) {
318
		return false;
319
	}
320
	foreach ($config['system']['user'] as & $user) {
321
		if ($user['uid'] == $uid) {
322
			return $user;
323
		}
324
	}
325

    
326
	return false;
327
}
328

    
329
function & getGroupEntry($name) {
330
	global $debug, $config, $groupindex;
331
	if (isset($groupindex[$name])) {
332
		return $config['system']['group'][$groupindex[$name]];
333
	}
334
}
335

    
336
function & getGroupEntryByGID($gid) {
337
	global $debug, $config;
338

    
339
	if (!is_array(array_get_path($config, 'system/group'))) {
340
		return false;
341
	}
342
	foreach ($config['system']['group'] as & $group) {
343
		if ($group['gid'] == $gid) {
344
			return $group;
345
		}
346
	}
347

    
348
	return false;
349
}
350

    
351
function get_user_privileges(& $user) {
352
	global $_SESSION;
353

    
354
	$authcfg = auth_get_authserver(config_get_path('system/webgui/authmode'));
355
	$allowed_groups = array();
356

    
357
	$privs = $user['priv'];
358
	if (!is_array($privs)) {
359
		$privs = array();
360
	}
361

    
362
	// cache auth results for a short time to ease load on auth services & logs
363
	$recheck_time = config_get_path('system/webgui/auth_refresh_time', 30);
364

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

    
385
	if (empty($allowed_groups)) {
386
		$allowed_groups = local_user_get_groups($user, true);
387
	}
388

    
389
	if (!is_array($allowed_groups)) {
390
		$allowed_groups = array('all');
391
	} else {
392
		$allowed_groups[] = 'all';
393
	}
394

    
395
	foreach ($allowed_groups as $name) {
396
		$group = getGroupEntry($name);
397
		if (is_array($group['priv'])) {
398
			$privs = array_merge($privs, $group['priv']);
399
		}
400
	}
401

    
402
	return $privs;
403
}
404

    
405
function userHasPrivilege($userent, $privid = false) {
406
	if (!$privid || !is_array($userent)) {
407
		return false;
408
	}
409

    
410
	$privs = get_user_privileges($userent);
411

    
412
	if (!is_array($privs)) {
413
		return false;
414
	}
415

    
416
	if (!in_array($privid, $privs)) {
417
		return false;
418
	}
419

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

    
432
	return true;
433
}
434

    
435
function local_backed($username, $passwd) {
436

    
437
	$user = getUserEntry($username);
438
	if (!$user) {
439
		return false;
440
	}
441

    
442
	if (is_account_disabled($username) || is_account_expired($username)) {
443
		return false;
444
	}
445

    
446
	if ($user['bcrypt-hash']) {
447
		if (password_verify($passwd, $user['bcrypt-hash'])) {
448
			return true;
449
		}
450
	}
451

    
452
	if ($user['sha512-hash']) {
453
		if (hash_equals($user['sha512-hash'], crypt($passwd, $user['sha512-hash']))) {
454
			return true;
455
		}
456
	}
457

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

    
465
	if ($user['md5-hash']) {
466
		if (hash_equals($user['md5-hash'], md5($passwd))) {
467
			return true;
468
		}
469
	}
470

    
471
	return false;
472
}
473

    
474
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
475
	global $debug;
476

    
477
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
478
		/* Nothing to be done here */
479
		return;
480
	}
481
	$users = config_get_path('system/user', []);
482
	$groups = config_get_path('system/group', []);
483

    
484
	foreach($u2del as $user) {
485
		if ($user['uid'] > 65000) {
486
			continue;
487
		} else if ($user['uid'] < 2000 && !in_array($user, $u2add)) {
488
			continue;
489
		}
490
		/* Don't remove /root */
491
		if ($user['uid'] != 0) {
492
			$rmhome = escapeshellarg('-r');
493
		} else {
494
			$rmhome = '';
495
		}
496

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

    
510
		for ($i = 0; $i < count($users); $i++) {
511
			if ($users[$i]['name'] == $user['name']) {
512
				log_error("Removing user: {$user['name']}");
513
				unset($users[$i]);
514
				break;
515
			}
516
		}
517
	}
518

    
519
	foreach($g2del as $group) {
520
		if ($group['gid'] < 2000 || $group['gid'] > 65000) {
521
			continue;
522
		}
523

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

    
531
		for ($i = 0; $i < count($groups); $i++) {
532
			if ($groups[$i]['name'] == $group['name']) {
533
				log_error("Removing group: {$group['name']}");
534
				unset($groups[$i]);
535
				break;
536
			}
537
		}
538
	}
539

    
540
	foreach ($u2add as $user) {
541
		log_error("Adding user: {$user['name']}");
542

    
543
		$users[] = $user;
544
	}
545

    
546
	foreach ($g2add as $group) {
547
		log_error("Adding group: {$group['name']}");
548
		$groups[] = $group;
549
	}
550

    
551
	/* Sort it alphabetically */
552
	usort($users, function($a, $b) {
553
		return strcmp($a['name'], $b['name']);
554
	});
555
	usort($groups, function($a, $b) {
556
		return strcmp($a['name'], $b['name']);
557
	});
558

    
559
	config_set_path('system/user', $users);
560
	config_set_path('system/group', $groups);
561
	write_config("Sync'd users and groups via XMLRPC");
562

    
563
	/* make sure the all group exists */
564
	$allgrp = getGroupEntryByGID(1998);
565
	local_group_set($allgrp, true);
566

    
567
	foreach ($u2add as $user) {
568
		local_user_set($user);
569
	}
570

    
571
	foreach ($g2add as $group) {
572
		local_group_set($group);
573
	}
574
}
575

    
576
function local_reset_accounts() {
577
	global $debug;
578

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

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

    
633
	/* make sure the all group exists */
634
	$allgrp = getGroupEntryByGID(1998);
635
	local_group_set($allgrp, true);
636

    
637
	/* sync all local users */
638
	foreach (config_get_path('system/user', []) as $user) {
639
		local_user_set($user);
640
	}
641

    
642
	/* sync all local groups */
643
	foreach (config_get_path('system/group', []) as $group) {
644
		local_group_set($group);
645
	}
646
}
647

    
648
function local_user_set(& $user) {
649
	global $g, $debug;
650

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

    
656

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

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

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

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

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

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

    
721
	$skel_dir = '/etc/skel';
722

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

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

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

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

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

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

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

    
789
}
790

    
791
function local_user_del($user) {
792
	global $debug;
793

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

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

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

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

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

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

    
822
function local_user_set_password(&$user, $password) {
823
	unset($user['password']);
824
	unset($user['md5-hash']);
825
	unset($user['sha512-hash']);
826
	unset($user['bcrypt-hash']);
827

    
828
	/* Default to bcrypt hashing if unset.
829
	 * See https://redmine.pfsense.org/issues/12855
830
	 */
831
	$hashalgo = config_get_path('system/webgui/pwhash', 'bcrypt');
832

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

    
844
	if (($user['name'] == config_get_path('hasync/username')) &&
845
	    (config_get_path('hasync/adminsync') == 'on')) {
846
		config_set_path('hasync/new_password', $password);
847
	}
848
}
849

    
850
function local_user_get_groups($user, $all = false) {
851
	$sysgroups = config_get_path('system/group', []);
852
	$groups = [];
853
	if(empty($sysgroups)) {
854
		return $groups;
855
	}
856

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

    
867
	if ($all) {
868
		$groups[] = "all";
869
	}
870

    
871
	sort($groups);
872

    
873
	return $groups;
874

    
875
}
876

    
877
function local_user_set_groups($user, $new_groups = NULL) {
878
	global $debug, $groupindex, $userindex;
879

    
880
	$groups = config_get_path('system/group', []);
881
	if (empty($groups)) {
882
		return;
883
	}
884

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

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

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

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

    
905
		/*
906
		 * If it's a new user, make sure it is added before try to
907
		 * add it as a member of a group
908
		 */
909
		if (!isset($userindex[$user['uid']])) {
910
			local_user_set($user);
911
		}
912
	}
913
	/* Clear $ngroup reference.
914
	 * https://redmine.pfsense.org/issues/14363 */
915
	unset($ngroup);
916

    
917
	/* determine which memberships to remove */
918
	foreach ($cur_groups as $groupname) {
919
		if (in_array($groupname, $new_groups)) {
920
			continue;
921
		}
922
		if (!isset($groups[$groupindex[$groupname]])) {
923
			continue;
924
		}
925
		$cgroup = &$groups[$groupindex[$groupname]];
926
		if (is_array($cgroup['member'])) {
927
			$index = array_search($user['uid'], $cgroup['member']);
928
			array_splice($cgroup['member'], $index, 1);
929
			$mod_groups[] = $cgroup;
930
		}
931
	}
932
	/* Clear $cgroup reference.
933
	 * https://redmine.pfsense.org/issues/14363 */
934
	unset($cgroup);
935

    
936
	config_set_path('system/group', $groups);
937

    
938
	/* sync all modified groups */
939
	foreach ($mod_groups as $mgroup) {
940
		local_group_set($mgroup);
941
	}
942
}
943

    
944
function local_group_del_user($user) {
945
	foreach (config_get_path('system/group', []) as $gid => $group) {
946
		foreach (array_get_path($group, 'member', []) as $idx => $uid) {
947
			if ($user['uid'] == $uid) {
948
				config_del_path("system/group/{$gid}/member/{$idx}");
949
				break;
950
			}
951
		}
952
	}
953
}
954

    
955
function local_group_set($group, $reset = false) {
956
	global $debug;
957

    
958
	$group_name = $group['name'];
959
	$group_gid = $group['gid'];
960
	$group_members = '';
961

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

    
966
	if (empty($group_name)) {
967
		return;
968
	}
969

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

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

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

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

    
993
	mwexec($cmd);
994
}
995

    
996
function local_group_del($group) {
997
	global $debug;
998

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

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

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

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

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

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

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

    
1043
	return true;
1044
}
1045

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

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

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

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

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

    
1109
	/* first check if there is even an LDAP server populated */
1110
	if (!$ldapserver) {
1111
		return false;
1112
	}
1113

    
1114
	/* connect and see if server is up */
1115
	$error = false;
1116
	if (!($ldap = ldap_connect($ldapserver))) {
1117
		$error = true;
1118
	}
1119

    
1120
	if ($error == true) {
1121
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1122
		return false;
1123
	}
1124

    
1125
	/* Setup CA environment if needed. */
1126
	ldap_setup_caenv($ldap, $authcfg);
1127

    
1128
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1129
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1130
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1131
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1132
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1133

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

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

    
1154
	@ldap_unbind($ldap);
1155

    
1156
	return true;
1157
}
1158

    
1159
function ldap_get_user_ous($show_complete_ou, $authcfg) {
1160
	if (!function_exists("ldap_connect")) {
1161
		return;
1162
	}
1163

    
1164
	$ous = array();
1165

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

    
1194
	/* first check if there is even an LDAP server populated */
1195
	if (!$ldapserver) {
1196
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1197
		return $ous;
1198
	}
1199

    
1200
	/* connect and see if server is up */
1201
	$error = false;
1202
	if (!($ldap = ldap_connect($ldapserver))) {
1203
		$error = true;
1204
	}
1205

    
1206
	if ($error == true) {
1207
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1208
		return $ous;
1209
	}
1210

    
1211
	/* Setup CA environment if needed. */
1212
	ldap_setup_caenv($ldap, $authcfg);
1213

    
1214
	$ldapfilter = "(|(ou=*)(cn=Users))";
1215

    
1216
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1217
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1218
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1219
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1220
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1221

    
1222
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1223
		if (!(@ldap_start_tls($ldap))) {
1224
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1225
			@ldap_close($ldap);
1226
			return false;
1227
		}
1228
	}
1229

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

    
1244
	if ($ldapscope == "one") {
1245
		$ldapfunc = "ldap_list";
1246
	} else {
1247
		$ldapfunc = "ldap_search";
1248
	}
1249

    
1250
	if (!($search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter))) {
1251
		goto errout;
1252
	}
1253

    
1254
	if (!is_array($info = @ldap_get_entries($ldap, $search))) {
1255
		goto errout;
1256
	}
1257

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

    
1274
errout: // goto to bailout early
1275

    
1276
	@ldap_unbind($ldap);
1277

    
1278
	return $ous;
1279
}
1280

    
1281
function ldap_get_groups($username, $authcfg) {
1282
	if (!function_exists("ldap_connect")) {
1283
		return array();
1284
	}
1285

    
1286
	if (!$username) {
1287
		return array();
1288
	}
1289

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

    
1295
	if (stristr($username, "\\")) {
1296
		$username_split = explode("\\", $username);
1297
		$username = $username_split[0];
1298
	}
1299

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

    
1332
	if (isset($authcfg['ldap_rfc2307'])) {
1333
		$ldapdn = $ldapbasedn;
1334
	} else {
1335
		$ldapdn = $_SESSION['ldapdn'];
1336
	}
1337

    
1338
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1339
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1340
	$memberof = array();
1341

    
1342
	/* connect and see if server is up */
1343
	$error = false;
1344
	if (!($ldap = ldap_connect($ldapserver))) {
1345
		$error = true;
1346
	}
1347

    
1348
	if ($error == true) {
1349
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1350
		return $memberof;
1351
	}
1352

    
1353
	/* Setup CA environment if needed. */
1354
	ldap_setup_caenv($ldap, $authcfg);
1355

    
1356
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1357
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1358
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1359
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1360
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1361

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

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

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

    
1395
	if (isset($authcfg['ldap_rfc2307'])) {
1396
		if (isset($authcfg['ldap_rfc2307_userdn'])) {
1397
			$has_userinfo = false;
1398
			$ldac_splits = explode(";", $ldapauthcont);
1399
			foreach ($ldac_splits as $i => $ldac_split) {
1400
				$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1401
				$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1402
				$ldapfilter = "({$ldapnameattribute}={$username})";
1403
				if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1404
					$ldapdn = $ldac_split;
1405
				} else {
1406
					$ldapdn = $ldapsearchbasedn;
1407
				}
1408
				if (($usersearch = @$ldapfunc($ldap, $ldapdn, $ldapfilter))) {
1409
					$userinfo = @ldap_get_entries($ldap, $usersearch);
1410
					$has_userinfo = true;
1411
				}
1412
			}
1413
			/* we can bailout early if the above query fails in rfc2307 mode */
1414
			if (!$has_userinfo) {
1415
				goto errout;
1416
			}
1417
			$username = $userinfo[0]['dn'];
1418
		}
1419
		$ldapfilter = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1420
	} else {
1421
		$ldapfilter = "({$ldapnameattribute}={$username})";
1422
	}
1423

    
1424
	if (!($search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute)))) {
1425
		goto errout;
1426
	}
1427

    
1428
	$info = @ldap_get_entries($ldap, $search);
1429
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1430

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

    
1442
errout: // goto to bailout early
1443

    
1444
	/* Time to close LDAP connection */
1445
	@ldap_unbind($ldap);
1446

    
1447
	$groups = print_r($memberof, true);
1448

    
1449
	return $memberof;
1450
}
1451

    
1452
function ldap_format_host($host) {
1453
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1454
}
1455

    
1456
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1457
	global $debug;
1458

    
1459
	if (!$username) {
1460
		$attributes['error_message'] = gettext("Invalid Login.");
1461
		return false;
1462
	}
1463

    
1464
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1465
		$attributes['error_message'] = gettext("Invalid credentials.");
1466
		return false;
1467
	}
1468

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

    
1475
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1476
		$username_split = explode("@", $username);
1477
		$username = $username_split[0];
1478
	}
1479
	if (stristr($username, "\\")) {
1480
		$username_split = explode("\\", $username);
1481
		$username = $username_split[0];
1482
	}
1483

    
1484
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1485

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

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

    
1537
	if ($debug) {
1538
		log_error(sprintf(gettext("LDAP Debug: Attempting to authenticate %s on %s"), $username, $ldapname));
1539
		log_error(sprintf(gettext("LDAP Debug: URI: %s (v%s)"), $ldapserver, $ldapver));
1540
		log_error(sprintf(gettext("LDAP Debug: Base DN: %s"), $ldapbasedn));
1541
		log_error(sprintf(gettext("LDAP Debug: Scope: %s"), $ldapscope));
1542
		log_error(sprintf(gettext("LDAP Debug: Auth Bind DN: %s"), $ldapbindun));
1543
		log_error(sprintf(gettext("LDAP Debug: Container: %s"), $ldapauthcont));
1544
		log_error(sprintf(gettext("LDAP Debug: Attrs: Name: %s / Group: %s"), $ldapnameattribute, $ldapgroupattribute));
1545
		log_error(sprintf(gettext("LDAP Debug: Extended Query: %s"), $ldapextendedquery));
1546
		log_error(sprintf(gettext("LDAP Debug: Filter: %s"), $ldapfilter));
1547
		log_error(sprintf(gettext("LDAP Debug: Group Filter: %s"), $ldapgroupfilter));
1548
	}
1549

    
1550
	/* Make sure we can connect to LDAP */
1551
	$error = false;
1552
	if (!($ldap = ldap_connect($ldapserver))) {
1553
		$error = true;
1554
	}
1555

    
1556
	if ($debug) {
1557
		log_error(sprintf(gettext("LDAP Debug: LDAP connection error flag: %s"), var_export($error, true)));
1558
	}
1559

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

    
1566
	/* Setup CA environment if needed. */
1567
	ldap_setup_caenv($ldap, $authcfg);
1568

    
1569
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1570
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1571
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1572
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1573
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1574

    
1575
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1576
		if (!(@ldap_start_tls($ldap))) {
1577
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1578
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1579
			@ldap_close($ldap);
1580
			return null;
1581
		}
1582
	}
1583

    
1584
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1585
	$error = false;
1586
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1587
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1588
	if ($ldapanon == true) {
1589
		if (!($res = @ldap_bind($ldap))) {
1590
			$error = true;
1591
		}
1592
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1593
		$error = true;
1594
	}
1595

    
1596
	if ($error == true) {
1597
		@ldap_close($ldap);
1598
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1599
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1600
		return null;
1601
	}
1602

    
1603
	/* Get LDAP Authcontainers and split em up. */
1604
	$ldac_splits = explode(";", $ldapauthcont);
1605

    
1606
	/* setup the usercount so we think we haven't found anyone yet */
1607
	$usercount = 0;
1608

    
1609
	/*****************************************************************/
1610
	/*  We first find the user based on username and filter          */
1611
	/*  then, once we find the first occurrence of that person       */
1612
	/*  we set session variables to point to the OU and DN of the    */
1613
	/*  person.  To later be used by ldap_get_groups.                */
1614
	/*  that way we don't have to search twice.                      */
1615
	/*****************************************************************/
1616
	if ($debug) {
1617
		log_error(sprintf(gettext("LDAP Debug: Now Searching for %s in directory."), $username));
1618
	}
1619
	/* Iterate through the user containers for search */
1620
	foreach ($ldac_splits as $i => $ldac_split) {
1621
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1622
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1623
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1624
		/* Make sure we just use the first user we find */
1625
		if ($debug) {
1626
			log_error(sprintf(gettext('LDAP Debug: Now searching in server %1$s, container %2$s with filter %3$s.'), $ldapname, utf8_decode($ldac_split), utf8_decode($ldapfilter)));
1627
		}
1628
		if ($ldapscope == "one") {
1629
			$ldapfunc = "ldap_list";
1630
		} else {
1631
			$ldapfunc = "ldap_search";
1632
		}
1633
		/* Support legacy auth container specification. */
1634
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1635
			$ldapdn = $ldac_split;
1636
		} else {
1637
			$ldapdn = $ldapsearchbasedn;
1638
		}
1639
		if (!($search = @$ldapfunc($ldap, $ldapdn, $ldapfilter))) {
1640
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1641
			continue;
1642
		}
1643
		if (isset($authcfg['ldap_rfc2307']) && isset($ldapgroupfilter)) {
1644
			if (isset($authcfg['ldap_rfc2307_userdn'])) {
1645
				$info = ldap_get_entries($ldap, $search);
1646
				$username = $info[0]['dn'];
1647
			}
1648
			$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1649
			$groupsearch = @$ldapfunc($ldap, $ldapdn, $ldapgroupfilter);
1650
			if ($debug) {
1651
				log_error(sprintf(gettext("LDAP Debug: RFC2307 group filter search: %s"), $ldapgroupfilter));
1652
			}
1653
		}
1654

    
1655
		if (isset($ldapgroupfilter) && !$groupsearch) {
1656
			log_error(sprintf(gettext("LDAP Debug: Extended group search resulted in error: %s"), ldap_error($ldap)));
1657
			continue;
1658
		}
1659
		if (isset($groupsearch)) {
1660
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1661
			if ($debug) {
1662
				log_error(sprintf(gettext("LDAP Debug: Group search contains %s results."), $validgroup));
1663
			}
1664
		}
1665
		$info = ldap_get_entries($ldap, $search);
1666
		$matches = $info['count'];
1667
		if ($matches == 1) {
1668
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1669
			$_SESSION['ldapou'] = $ldac_split[$i];
1670
			$_SESSION['ldapon'] = "true";
1671
			$usercount = 1;
1672
			break;
1673
		}
1674
	}
1675

    
1676
	if ($usercount != 1) {
1677
		@ldap_unbind($ldap);
1678
		if ($debug) {
1679
			if ($usercount === 0) {
1680
				log_error(sprintf(gettext("LDAP Debug: ERROR! LDAP search failed, no user matching %s was found."), $username));
1681
			} else {
1682
				log_error(sprintf(gettext("LDAP Debug: ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1683
			}
1684
		}
1685
		$attributes['error_message'] = gettext("Invalid login specified.");
1686
		return false;
1687
	}
1688

    
1689
	/* Now lets bind as the user we found */
1690
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1691
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1692
		if ($debug) {
1693
			log_error(sprintf(gettext('LDAP Debug: ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1694
		}
1695
		@ldap_unbind($ldap);
1696
		return false;
1697
	}
1698

    
1699
	if ($debug) {
1700
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1701
		log_error(sprintf(gettext('LDAP Debug: Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1702
	}
1703

    
1704
	if ($debug && isset($ldapgroupfilter) && $validgroup < 1) {
1705
		log_error(sprintf(gettext('LDAP Debug: Logged in successfully as %1$s but did not match any field in extended query.'), $username));
1706
	}
1707

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

    
1711
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1712
		return false;
1713
	}
1714

    
1715
	return true;
1716
}
1717

    
1718
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1719
	$ret = false;
1720

    
1721
	require_once("Auth/RADIUS.php");
1722
	require_once("Crypt/CHAP.php");
1723

    
1724
	if ($authcfg) {
1725
		$radiusservers = array();
1726
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1727
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1728
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1729
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1730
		if(isset($authcfg['radius_protocol'])) {
1731
			$radius_protocol = $authcfg['radius_protocol'];
1732
		} else {
1733
			$radius_protocol = 'PAP';
1734
		}
1735
	} else {
1736
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1737
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1738
		return null;
1739
	}
1740

    
1741
	// Create our instance
1742
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1743
	$rauth = new $classname($username, $password);
1744

    
1745
	/* Add new servers to our instance */
1746
	foreach ($radiusservers as $radsrv) {
1747
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1748
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1749
	}
1750

    
1751
	// Construct data package
1752
	$rauth->username = $username;
1753
	switch ($radius_protocol) {
1754
		case 'CHAP_MD5':
1755
		case 'MSCHAPv1':
1756
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1757
			$crpt = new $classname;
1758
			$crpt->username = $username;
1759
			$crpt->password = $password;
1760
			$rauth->challenge = $crpt->challenge;
1761
			$rauth->chapid = $crpt->chapid;
1762
			$rauth->response = $crpt->challengeResponse();
1763
			$rauth->flags = 1;
1764
			break;
1765

    
1766
		case 'MSCHAPv2':
1767
			$crpt = new Crypt_CHAP_MSv2;
1768
			$crpt->username = $username;
1769
			$crpt->password = $password;
1770
			$rauth->challenge = $crpt->authChallenge;
1771
			$rauth->peerChallenge = $crpt->peerChallenge;
1772
			$rauth->chapid = $crpt->chapid;
1773
			$rauth->response = $crpt->challengeResponse();
1774
			break;
1775

    
1776
		default:
1777
			$rauth->password = $password;
1778
			break;
1779
	}
1780

    
1781
	if (PEAR::isError($rauth->start())) {
1782
		$ret = null;
1783
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1784
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1785
	} else {
1786
		$nasid = $attributes['nas_identifier'];
1787
		if (empty($nasid)) {
1788
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1789
		}
1790
		$nasip = nasip_fallback($authcfg['radius_nasip_attribute']);
1791
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1792

    
1793
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1794
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1795

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

    
1815
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1816

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

    
1829

    
1830
	// Get attributes, even if auth failed.
1831
	if ($rauth->getAttributes()) {
1832
	$attributes = array_merge($attributes,$rauth->listAttributes());
1833

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

    
1841
	// close OO RADIUS_AUTHENTICATION
1842
	$rauth->close();
1843

    
1844
	return $ret;
1845
}
1846

    
1847
function nasip_fallback($ip) {
1848
	if (!is_ipaddr($ip)) {
1849
		$nasip = get_interface_ip($ip);
1850

    
1851
		if (!is_ipaddr($nasip)) {
1852
			/* use first interface with IP as fallback for NAS-IP-Address
1853
			 * see https://redmine.pfsense.org/issues/11109 */
1854
			foreach (get_configured_interface_list() as $if) {
1855
				$nasip = get_interface_ip($if);
1856
				if (is_ipaddr($nasip)) {
1857
					break;
1858
				}
1859
			}
1860
		}
1861
	} else {
1862
		$nasip = $ip;
1863
	}
1864

    
1865
	return $nasip;
1866
}
1867

    
1868
/*
1869
	$attributes must contain a "class" key containing the groups and local
1870
	groups must exist to match.
1871
*/
1872
function radius_get_groups($attributes) {
1873
	$groups = array();
1874
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1875
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1876
		$groups = array();
1877
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1878
			foreach ($attributes['class'] as $class) {
1879
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1880
			}
1881
		}
1882

    
1883
		foreach ($groups as & $grp) {
1884
			$grp = trim($grp);
1885
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1886
				$grp = substr($grp, 3);
1887
			}
1888
		}
1889
	}
1890
	return $groups;
1891
}
1892

    
1893
function get_user_expiration_date($username) {
1894
	$user = getUserEntry($username);
1895
	if ($user['expires']) {
1896
		return $user['expires'];
1897
	}
1898
}
1899

    
1900
function is_account_expired($username) {
1901
	$expirydate = get_user_expiration_date($username);
1902
	if ($expirydate) {
1903
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1904
			return true;
1905
		}
1906
	}
1907

    
1908
	return false;
1909
}
1910

    
1911
function is_account_disabled($username) {
1912
	$user = getUserEntry($username);
1913
	if (isset($user['disabled'])) {
1914
		return true;
1915
	}
1916

    
1917
	return false;
1918
}
1919

    
1920
function get_user_settings($username) {
1921
	$settings = array();
1922
	$settings['widgets'] = config_get_path('widgets');
1923
	$settings['webgui']['dashboardcolumns'] = config_get_path('system/webgui/dashboardcolumns');
1924
	$settings['webgui']['webguihostnamemenu'] = config_get_path('system/webgui/webguihostnamemenu');
1925
	$settings['webgui']['webguicss'] = config_get_path('system/webgui/webguicss');
1926
	$settings['webgui']['logincss'] = config_get_path('system/webgui/logincss');
1927
	$settings['webgui']['interfacessort'] = config_path_enabled('system/webgui', 'interfacessort');
1928
	$settings['webgui']['dashboardavailablewidgetspanel'] = config_path_enabled('system/webgui', 'dashboardavailablewidgetspanel');
1929
	$settings['webgui']['webguifixedmenu'] = config_path_enabled('system/webgui', 'webguifixedmenu');
1930
	$settings['webgui']['webguileftcolumnhyper'] = config_path_enabled('system/webgui', 'webguileftcolumnhyper');
1931
	$settings['webgui']['disablealiaspopupdetail'] = config_path_enabled('system/webgui', 'disablealiaspopupdetail');
1932
	$settings['webgui']['systemlogsfilterpanel'] = config_path_enabled('system/webgui', 'systemlogsfilterpanel');
1933
	$settings['webgui']['systemlogsmanagelogpanel'] = config_path_enabled('system/webgui', 'systemlogsmanagelogpanel');
1934
	$settings['webgui']['statusmonitoringsettingspanel'] = config_path_enabled('system/webgui', 'statusmonitoringsettingspanel');
1935
	$settings['webgui']['pagenamefirst'] = config_path_enabled('system/webgui', 'pagenamefirst');
1936
	$user = getUserEntry($username);
1937
	if (isset($user['customsettings'])) {
1938
		$settings['customsettings'] = true;
1939
		if (isset($user['widgets'])) {
1940
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1941
			$settings['widgets'] = $user['widgets'];
1942
		}
1943
		if (isset($user['dashboardcolumns'])) {
1944
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1945
		}
1946
		if (isset($user['webguicss'])) {
1947
			$settings['webgui']['webguicss'] = $user['webguicss'];
1948
		}
1949
		if (isset($user['webguihostnamemenu'])) {
1950
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1951
		}
1952
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1953
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1954
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1955
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1956
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1957
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1958
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1959
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1960
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1961
	} else {
1962
		$settings['customsettings'] = false;
1963
	}
1964

    
1965
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1966
		$settings['webgui']['dashboardcolumns'] = 2;
1967
	}
1968

    
1969
	return $settings;
1970
}
1971

    
1972
function save_widget_settings($username, $settings, $message = "") {
1973
	global $userindex;
1974
	$user = getUserEntry($username);
1975

    
1976
	if (strlen($message) > 0) {
1977
		$msgout = $message;
1978
	} else {
1979
		$msgout = gettext("Widget configuration has been changed.");
1980
	}
1981

    
1982
	if (isset($user['customsettings'])) {
1983
		config_set_path("system/user/{$userindex[$username]}/widgets", $settings);
1984
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1985
	} else {
1986
		config_set_path('widgets', $settings);
1987
		write_config($msgout);
1988
	}
1989
}
1990

    
1991
function auth_get_authserver($name) {
1992
	foreach (config_get_path('system/authserver', []) as $authcfg) {
1993
		if ($authcfg['name'] == $name) {
1994
			return $authcfg;
1995
		}
1996
	}
1997
	if ($name == "Local Database") {
1998
		return array("name" => "Local Database", "type" => "Local Auth", "host" => config_get_path('system/hostname'));
1999
	}
2000
}
2001

    
2002
function auth_get_authserver_list() {
2003
	$list = array();
2004

    
2005
	foreach (config_get_path('system/authserver', []) as $authcfg) {
2006
		/* Add support for disabled entries? */
2007
		$list[$authcfg['name']] = $authcfg;
2008
	}
2009

    
2010
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => config_get_path('system/hostname'));
2011
	return $list;
2012
}
2013

    
2014
function getUserGroups($username, $authcfg, &$attributes = array()) {
2015
	$allowed_groups = array();
2016

    
2017
	switch ($authcfg['type']) {
2018
		case 'ldap':
2019
			$allowed_groups = @ldap_get_groups($username, $authcfg);
2020
			break;
2021
		case 'radius':
2022
			$allowed_groups = @radius_get_groups($attributes);
2023
			break;
2024
		default:
2025
			$user = getUserEntry($username);
2026
			$allowed_groups = @local_user_get_groups($user, true);
2027
			break;
2028
	}
2029

    
2030
	$member_groups = array();
2031
	foreach (config_get_path('system/group', []) as $group) {
2032
		if (in_array($group['name'], $allowed_groups)) {
2033
			$member_groups[] = $group['name'];
2034
		}
2035
	}
2036

    
2037
	return $member_groups;
2038
}
2039

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

    
2048
	if (is_array($username) || is_array($password)) {
2049
		return false;
2050
	}
2051

    
2052
	if (!$authcfg) {
2053
		return local_backed($username, $password, $attributes);
2054
	}
2055

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

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

    
2084
	return $authenticated;
2085
}
2086

    
2087
function session_auth() {
2088
	global $_SESSION, $page;
2089

    
2090
	// Handle HTTPS httponly and secure flags
2091
	$currentCookieParams = session_get_cookie_params();
2092
	session_set_cookie_params(
2093
		$currentCookieParams["lifetime"],
2094
		$currentCookieParams["path"],
2095
		NULL,
2096
		(config_get_path('system/webgui/protocol') == "https"),
2097
		true
2098
	);
2099

    
2100
	phpsession_begin();
2101

    
2102
	// Detect protocol change
2103
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != config_get_path('system/webgui/protocol')) {
2104
		phpsession_end();
2105
		return false;
2106
	}
2107

    
2108
	// Detect IP change
2109
	if ((!isset($_POST['login'])) && (config_get_path('system/webgui/roaming') == 'disabled') && (!empty($_SESSION['REMOTE_ADDR']) && $_SESSION['REMOTE_ADDR'] != $_SERVER['REMOTE_ADDR'])) {
2110
		phpsession_end();
2111
		return false;
2112
	}
2113

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

    
2160
	/* Show login page if they aren't logged in */
2161
	if (empty($_SESSION['Logged_In'])) {
2162
		phpsession_end(true);
2163
		return false;
2164
	}
2165

    
2166
	$session_timeout = config_get_path('system/webgui/session_timeout', 240);
2167
	/* If session timeout isn't set, we don't mark sessions stale */
2168
	if (intval($session_timeout) == 0) {
2169
		/* only update if it wasn't ajax */
2170
		if (!isAjax()) {
2171
			$_SESSION['last_access'] = time();
2172
		}
2173
	} else {
2174
		/* Check for stale session */
2175
		if ($_SESSION['last_access'] < (time() - ($session_timeout * 60))) {
2176
			$_POST['logout'] = true;
2177
			$_SESSION['Logout'] = true;
2178
		} else {
2179
			/* only update if it wasn't ajax */
2180
			if (!isAjax()) {
2181
				$_SESSION['last_access'] = time();
2182
			}
2183
		}
2184
	}
2185

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

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

    
2195
		/* wipe out $_SESSION */
2196
		$_SESSION = array();
2197

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

    
2202
		/* and destroy it */
2203
		phpsession_destroy();
2204

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

    
2209
		if (isAjax()) {
2210
			return false;
2211
		}
2212

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

    
2216
		return false;
2217
	}
2218

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

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

    
2238
function print_credit() {
2239
	global $g;
2240

    
2241
	return  '<a target="_blank" href="https://pfsense.org">' . g_get('product_label') . '</a>' .
2242
			gettext(' is developed and maintained by ') .
2243
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . g_get('product_copyright_years') .
2244
			'<a target="_blank" href="https://pfsense.org/license">' .
2245
			gettext(' View license.') . '</a>';
2246
}
2247
function get_user_remote_address($print_all=true) {
2248
	$remote_address = $_SERVER['REMOTE_ADDR'];
2249
	/* Add extra identifying header information upon request */
2250
	if ($print_all) {
2251
		if (!empty($_SERVER['HTTP_CLIENT_IP'] &&
2252
		    is_ipaddr($_SERVER['HTTP_CLIENT_IP']))) {
2253
			$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2254
		} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) &&
2255
			  is_ipaddr($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2256
			$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2257
		}
2258
	}
2259
	return $remote_address;
2260
}
2261
function get_user_remote_authsource() {
2262
	$authsource = "";
2263
	if (!empty($_SESSION['authsource'])) {
2264
		$authsource .= " ({$_SESSION['authsource']})";
2265
	}
2266
	return $authsource;
2267
}
2268

    
2269
function set_pam_auth() {
2270
	$authcfg = auth_get_authserver(config_get_path('system/webgui/authmode'));
2271

    
2272
	unlink_if_exists("/etc/radius.conf");
2273
	unlink_if_exists("/var/etc/pam_ldap.conf");
2274
	unlink_if_exists("/var/etc/pam_ldap_ca.crt");
2275

    
2276
	$header = "# This file is automatically generated. Do not edit.\n\n";
2277
	$pam_sshd =<<<EOD
2278
# auth
2279
auth		required	pam_unix.so		no_warn try_first_pass
2280

    
2281
# account
2282
account		required	pam_nologin.so
2283
account		required	pam_login_access.so
2284
account		required	pam_unix.so
2285

    
2286
# session
2287
session		required	pam_permit.so
2288

    
2289
# password
2290
password	required	pam_unix.so		no_warn try_first_pass
2291

    
2292
EOD;
2293

    
2294
	$pam_system =<<<EOD
2295
# auth
2296
auth		required	pam_unix.so		no_warn try_first_pass
2297

    
2298
# account
2299
account		required	pam_login_access.so
2300
account		required	pam_unix.so
2301

    
2302
# session
2303
session		required	pam_lastlog.so		no_fail
2304

    
2305
# password
2306
password	required	pam_unix.so		no_warn try_first_pass
2307

    
2308
EOD;
2309

    
2310
	$nsswitch =<<<EOD
2311
group: files
2312
hosts: files dns
2313
netgroup: files
2314
networks: files
2315
passwd: files
2316
shells: files
2317
services: files
2318
protocols: files
2319
rpc: files
2320

    
2321
EOD;
2322

    
2323
	if (config_path_enabled('system/webgui', 'shellauth')) {
2324
		if (($authcfg['type'] == "radius") && isset($authcfg['radius_auth_port'])) {
2325
			$radius_conf = "auth {$authcfg['host']}:{$authcfg['radius_auth_port']} " .
2326
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2327
			if (isset($authcfg['radius_acct_port'])) {
2328
				$radius_conf .= "acct {$authcfg['host']}:{$authcfg['radius_acct_port']} " .
2329
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2330
			}
2331

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

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

    
2342
# session
2343
session		required	pam_permit.so
2344

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

    
2349
EOD;
2350

    
2351
			$pam_system =<<<EOD
2352
# auth
2353
auth            sufficient      pam_radius.so
2354
auth		required	pam_unix.so		no_warn try_first_pass
2355

    
2356
# account
2357
account		required	pam_login_access.so
2358
account         sufficient      pam_radius.so
2359

    
2360
# session
2361
session		required	pam_lastlog.so		no_fail
2362

    
2363
# password
2364
password        sufficient      pam_radius.so
2365
password	required	pam_unix.so		no_warn try_first_pass
2366

    
2367
EOD;
2368

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

    
2409
			$pam_sshd =<<<EOD
2410
# auth
2411
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2412
auth		required	pam_unix.so		no_warn try_first_pass
2413

    
2414
# account
2415
account		required	pam_nologin.so
2416
account		required	pam_login_access.so
2417
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2418

    
2419
# session
2420
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2421
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2422
session		required	pam_permit.so
2423

    
2424
# password
2425
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2426
password	required	pam_unix.so		no_warn try_first_pass
2427

    
2428
EOD;
2429

    
2430
			$pam_system =<<<EOD
2431
# auth
2432
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2433
auth		required	pam_unix.so		no_warn try_first_pass
2434

    
2435
# account
2436
account		required	pam_login_access.so
2437
account         sufficient      pam_radius.so
2438
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2439

    
2440
# session
2441
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2442
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2443
session		required	pam_lastlog.so		no_fail
2444

    
2445
# password
2446
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2447
password	required	pam_unix.so		no_warn try_first_pass
2448

    
2449
EOD;
2450

    
2451
			$nsswitch =<<<EOD
2452
group: files ldap
2453
hosts: files dns
2454
netgroup: files
2455
networks: files
2456
passwd: files ldap
2457
shells: files
2458
services: files
2459
protocols: files
2460
rpc: files
2461

    
2462
EOD;
2463

    
2464
			@file_put_contents("/var/etc/pam_ldap.conf", $ldapconf);
2465
			@chmod("/var/etc/pam_ldap.conf", 0600);
2466
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2467
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2468
		}
2469
	}
2470

    
2471
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2472
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2473
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2474
}
2475
?>
(2-2/61)