Project

General

Profile

Download (71.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * auth.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2003-2006 Manuel Kasper <mk@neon1.net>
7
 * Copyright (c) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 * Copyright (c) 2006 Paul Taylor <paultaylor@winn-dixie.com>
9
 * Copyright (c) 2004-2013 BSD Perimeter
10
 * Copyright (c) 2013-2016 Electric Sheep Fencing
11
 * Copyright (c) 2014-2022 Rubicon Communications, LLC (Netgate)
12
 * All rights reserved.
13
 *
14
 * Licensed under the Apache License, Version 2.0 (the "License");
15
 * you may not use this file except in compliance with the License.
16
 * You may obtain a copy of the License at
17
 *
18
 * http://www.apache.org/licenses/LICENSE-2.0
19
 *
20
 * Unless required by applicable law or agreed to in writing, software
21
 * distributed under the License is distributed on an "AS IS" BASIS,
22
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
 * See the License for the specific language governing permissions and
24
 * limitations under the License.
25
 */
26

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

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

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

    
45
	/* Fetch the contents of the lockout table. */
46
	$entries = array();
47
	exec("/sbin/pfctl -t 'sshguard' -T show", $entries);
48

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
252
$groupindex = index_groups();
253
$userindex = index_users();
254

    
255
function index_groups() {
256
	global $g, $debug, $config, $groupindex;
257

    
258
	$groupindex = array();
259

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

    
268
	return ($groupindex);
269
}
270

    
271
function index_users() {
272
	global $g, $debug, $config;
273

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

    
282
	return ($userindex);
283
}
284

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

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

    
298
function & getUserEntryByUID($uid) {
299
	global $debug, $config;
300

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

    
309
	return false;
310
}
311

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

    
319
function & getGroupEntryByGID($gid) {
320
	global $debug, $config;
321

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

    
330
	return false;
331
}
332

    
333
function get_user_privileges(& $user) {
334
	global $config, $_SESSION;
335

    
336
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
337
	$allowed_groups = array();
338

    
339
	$privs = $user['priv'];
340
	if (!is_array($privs)) {
341
		$privs = array();
342
	}
343

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

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

    
371
	if (empty($allowed_groups)) {
372
		$allowed_groups = local_user_get_groups($user, true);
373
	}
374

    
375
	if (!is_array($allowed_groups)) {
376
		$allowed_groups = array('all');
377
	} else {
378
		$allowed_groups[] = 'all';
379
	}
380

    
381
	foreach ($allowed_groups as $name) {
382
		$group = getGroupEntry($name);
383
		if (is_array($group['priv'])) {
384
			$privs = array_merge($privs, $group['priv']);
385
		}
386
	}
387

    
388
	return $privs;
389
}
390

    
391
function userHasPrivilege($userent, $privid = false) {
392
	global $config;
393

    
394
	if (!$privid || !is_array($userent)) {
395
		return false;
396
	}
397

    
398
	$privs = get_user_privileges($userent);
399

    
400
	if (!is_array($privs)) {
401
		return false;
402
	}
403

    
404
	if (!in_array($privid, $privs)) {
405
		return false;
406
	}
407

    
408
	/* If someone is in admins group or is admin, do not honor the
409
	 * user-config-readonly privilege to prevent foot-shooting due to a
410
	 * bad privilege config.
411
	 * https://redmine.pfsense.org/issues/10492 */
412
	$userGroups = getUserGroups($userent['name'],
413
			auth_get_authserver($config['system']['webgui']['authmode']),
414
			$_SESSION['user_radius_attributes']);
415
	if (($privid == 'user-config-readonly') &&
416
	    (($userent['uid'] === "0") || (in_array('admins', $userGroups)))) {
417
		return false;
418
	}
419

    
420
	return true;
421
}
422

    
423
function local_backed($username, $passwd) {
424

    
425
	$user = getUserEntry($username);
426
	if (!$user) {
427
		return false;
428
	}
429

    
430
	if (is_account_disabled($username) || is_account_expired($username)) {
431
		return false;
432
	}
433

    
434
	if ($user['sha512-hash']) {
435
		if (hash_equals($user['sha512-hash'], crypt($passwd, $user['sha512-hash']))) {
436
			return true;
437
		}
438
	}
439

    
440
	//for backwards compatibility
441
	if ($user['bcrypt-hash']) {
442
		if (password_verify($passwd, $user['bcrypt-hash'])) {
443
			return true;
444
		}
445
	}
446

    
447
	// pfSense < 2.3 password hashing, see https://redmine.pfsense.org/issues/4120
448
	if ($user['password']) {
449
		if (hash_equals($user['password'], crypt($passwd, $user['password']))) {
450
			return true;
451
		}
452
	}
453

    
454
	if ($user['md5-hash']) {
455
		if (hash_equals($user['md5-hash'], md5($passwd))) {
456
			return true;
457
		}
458
	}
459

    
460
	return false;
461
}
462

    
463
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
464
	global $config, $debug;
465

    
466
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
467
		/* Nothing to be done here */
468
		return;
469
	}
470

    
471
	foreach($u2del as $user) {
472
		if ($user['uid'] > 65000) {
473
			continue;
474
		} else if ($user['uid'] < 2000 && !in_array($user, $u2add)) {
475
			continue;
476
		}
477

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

    
492
		$system_user = $config['system']['user'];
493
		for ($i = 0; $i < count($system_user); $i++) {
494
			if ($system_user[$i]['name'] == $user['name']) {
495
				log_error("Removing user: {$user['name']}");
496
				unset($config['system']['user'][$i]);
497
				break;
498
			}
499
		}
500
	}
501

    
502
	foreach($g2del as $group) {
503
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
504
			continue;
505
		}
506

    
507
		$cmd = "/usr/sbin/pw groupdel -g " .
508
		    escapeshellarg($group['name']);
509
		if ($debug) {
510
			log_error(sprintf(gettext("Running: %s"), $cmd));
511
		}
512
		mwexec($cmd);
513

    
514
		$system_group = $config['system']['group'];
515
		for ($i = 0; $i < count($system_group); $i++) {
516
			if ($system_group[$i]['name'] == $group['name']) {
517
				log_error("Removing group: {$group['name']}");
518
				unset($config['system']['group'][$i]);
519
				break;
520
			}
521
		}
522
	}
523

    
524
	foreach ($u2add as $user) {
525
		log_error("Adding user: {$user['name']}");
526
		$config['system']['user'][] = $user;
527
	}
528

    
529
	foreach ($g2add as $group) {
530
		log_error("Adding group: {$group['name']}");
531
		$config['system']['group'][] = $group;
532
	}
533

    
534
	/* Sort it alphabetically */
535
	usort($config['system']['user'], function($a, $b) {
536
		return strcmp($a['name'], $b['name']);
537
	});
538
	usort($config['system']['group'], function($a, $b) {
539
		return strcmp($a['name'], $b['name']);
540
	});
541

    
542
	write_config("Sync'd users and groups via XMLRPC");
543

    
544
	/* make sure the all group exists */
545
	$allgrp = getGroupEntryByGID(1998);
546
	local_group_set($allgrp, true);
547

    
548
	foreach ($u2add as $user) {
549
		local_user_set($user);
550
	}
551

    
552
	foreach ($g2add as $group) {
553
		local_group_set($group);
554
	}
555
}
556

    
557
function local_reset_accounts() {
558
	global $debug, $config;
559

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

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

    
614
	/* make sure the all group exists */
615
	$allgrp = getGroupEntryByGID(1998);
616
	local_group_set($allgrp, true);
617

    
618
	/* sync all local users */
619
	if (is_array($config['system']['user'])) {
620
		foreach ($config['system']['user'] as $user) {
621
			local_user_set($user);
622
		}
623
	}
624

    
625
	/* sync all local groups */
626
	if (is_array($config['system']['group'])) {
627
		foreach ($config['system']['group'] as $group) {
628
			local_group_set($group);
629
		}
630
	}
631
}
632

    
633
function local_user_set(& $user) {
634
	global $g, $debug;
635

    
636
	if (empty($user['sha512-hash']) && empty($user['bcrypt-hash']) && empty($user['password'])) {
637
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
638
		return;
639
	}
640

    
641

    
642
	$home_base = "/home/";
643
	$user_uid = $user['uid'];
644
	$user_name = $user['name'];
645
	$user_home = "{$home_base}{$user_name}";
646
	$user_shell = "/etc/rc.initial";
647
	$user_group = "nobody";
648

    
649
	// Ensure $home_base exists and is writable
650
	if (!is_dir($home_base)) {
651
		mkdir($home_base, 0755);
652
	}
653

    
654
	$lock_account = false;
655
	/* configure shell type */
656
	/* Cases here should be ordered by most privileged to least privileged. */
657
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
658
		$user_shell = "/bin/tcsh";
659
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
660
		$user_shell = "/usr/local/sbin/scponlyc";
661
	} elseif (userHasPrivilege($user, "user-copy-files")) {
662
		$user_shell = "/usr/local/bin/scponly";
663
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
664
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
665
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
666
		$user_shell = "/sbin/nologin";
667
	} else {
668
		$user_shell = "/sbin/nologin";
669
		$lock_account = true;
670
	}
671

    
672
	/* Lock out disabled or expired users, unless it's root/admin. */
673
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
674
		$user_shell = "/sbin/nologin";
675
		$lock_account = true;
676
	}
677

    
678
	/* root user special handling */
679
	if ($user_uid == 0) {
680
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
681
		if ($debug) {
682
			log_error(sprintf(gettext("Running: %s"), $cmd));
683
		}
684
		$fd = popen($cmd, "w");
685
		if (isset($user['sha512-hash'])) {
686
			fwrite($fd, $user['sha512-hash']);
687
		} elseif (isset($user['bcrypt-hash'])) {
688
			fwrite($fd, $user['bcrypt-hash']);
689
		} else {
690
			fwrite($fd, $user['password']);
691
		}
692
		pclose($fd);
693
		$user_group = "wheel";
694
		$user_home = "/root";
695
		$user_shell = "/etc/rc.initial";
696
	}
697

    
698
	/* read from pw db */
699
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
700
	$pwread = fgets($fd);
701
	pclose($fd);
702
	$userattrs = explode(":", trim($pwread));
703

    
704
	$skel_dir = '/etc/skel';
705

    
706
	/* determine add or mod */
707
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
708
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
709
	} else {
710
		$user_op = "usermod";
711
	}
712

    
713
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
714
	/* add or mod pw db */
715
	$cmd = "/usr/sbin/pw {$user_op} -q " .
716
			" -u " . escapeshellarg($user_uid) .
717
			" -n " . escapeshellarg($user_name) .
718
			" -g " . escapeshellarg($user_group) .
719
			" -s " . escapeshellarg($user_shell) .
720
			" -d " . escapeshellarg($user_home) .
721
			" -c " . escapeshellarg($comment) .
722
			" -H 0 2>&1";
723

    
724
	if ($debug) {
725
		log_error(sprintf(gettext("Running: %s"), $cmd));
726
	}
727
	$fd = popen($cmd, "w");
728
	if (isset($user['sha512-hash'])) {
729
		fwrite($fd, $user['sha512-hash']);
730
	} elseif (isset($user['bcrypt-hash'])) {
731
		fwrite($fd, $user['bcrypt-hash']);
732
	} else {
733
		fwrite($fd, $user['password']);
734
	}
735
	pclose($fd);
736

    
737
	/* create user directory if required */
738
	if (!is_dir($user_home)) {
739
		mkdir($user_home, 0700);
740
	}
741
	@chown($user_home, $user_name);
742
	@chgrp($user_home, $user_group);
743

    
744
	/* Make sure all users have last version of config files */
745
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
746
		$target = $user_home . '/' . substr(basename($dot_file), 3);
747
		@copy($dot_file, $target);
748
		@chown($target, $user_name);
749
		@chgrp($target, $user_group);
750
	}
751

    
752
	/* write out ssh authorized key file */
753
	if ($user['authorizedkeys']) {
754
		if (!is_dir("{$user_home}/.ssh")) {
755
			@mkdir("{$user_home}/.ssh", 0700);
756
			@chown("{$user_home}/.ssh", $user_name);
757
		}
758
		$keys = base64_decode($user['authorizedkeys']);
759
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
760
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
761
	} else {
762
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
763
	}
764

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

    
768
}
769

    
770
function local_user_del($user) {
771
	global $debug;
772

    
773
	/* remove all memberships */
774
	local_user_set_groups($user);
775

    
776
	/* Don't remove /root */
777
	if ($user['uid'] != 0) {
778
		$rmhome = "-r";
779
	}
780

    
781
	/* read from pw db */
782
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
783
	$pwread = fgets($fd);
784
	pclose($fd);
785
	$userattrs = explode(":", trim($pwread));
786

    
787
	if ($userattrs[0] != $user['name']) {
788
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
789
		return;
790
	}
791

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

    
795
	if ($debug) {
796
		log_error(sprintf(gettext("Running: %s"), $cmd));
797
	}
798
	mwexec($cmd);
799

    
800
	/* Delete user from groups needs a call to write_config() */
801
	local_group_del_user($user);
802
}
803

    
804
function local_user_set_password(&$user, $password) {
805
	global $config;
806

    
807
	unset($user['password']);
808
	unset($user['md5-hash']);
809
	unset($user['bcrypt-hash']);
810
	$salt = substr(bin2hex(openssl_random_pseudo_bytes(16)),0,16);
811
	$user['sha512-hash'] = crypt($password, '$6$'. $salt . '$');
812
	if (($user['name'] == $config['hasync']['username']) &&
813
	    ($config['hasync']['adminsync'] == 'on')) {
814
		$config['hasync']['new_password'] = $password;
815
	}
816
}
817

    
818
function local_user_get_groups($user, $all = false) {
819
	global $debug, $config;
820

    
821
	$groups = array();
822
	if (!is_array($config['system']['group'])) {
823
		return $groups;
824
	}
825

    
826
	foreach ($config['system']['group'] as $group) {
827
		if ($all || (!$all && ($group['name'] != "all"))) {
828
			if (is_array($group['member'])) {
829
				if (in_array($user['uid'], $group['member'])) {
830
					$groups[] = $group['name'];
831
				}
832
			}
833
		}
834
	}
835

    
836
	if ($all) {
837
		$groups[] = "all";
838
	}
839

    
840
	sort($groups);
841

    
842
	return $groups;
843

    
844
}
845

    
846
function local_user_set_groups($user, $new_groups = NULL) {
847
	global $debug, $config, $groupindex, $userindex;
848

    
849
	if (!is_array($config['system']['group'])) {
850
		return;
851
	}
852

    
853
	$cur_groups = local_user_get_groups($user, true);
854
	$mod_groups = array();
855

    
856
	if (!is_array($new_groups)) {
857
		$new_groups = array();
858
	}
859

    
860
	if (!is_array($cur_groups)) {
861
		$cur_groups = array();
862
	}
863

    
864
	/* determine which memberships to add */
865
	foreach ($new_groups as $groupname) {
866
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
867
			continue;
868
		}
869
		$group = &$config['system']['group'][$groupindex[$groupname]];
870
		$group['member'][] = $user['uid'];
871
		$mod_groups[] = $group;
872

    
873
		/*
874
		 * If it's a new user, make sure it is added before try to
875
		 * add it as a member of a group
876
		 */
877
		if (!isset($userindex[$user['uid']])) {
878
			local_user_set($user);
879
		}
880
	}
881
	unset($group);
882

    
883
	/* determine which memberships to remove */
884
	foreach ($cur_groups as $groupname) {
885
		if (in_array($groupname, $new_groups)) {
886
			continue;
887
		}
888
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
889
			continue;
890
		}
891
		$group = &$config['system']['group'][$groupindex[$groupname]];
892
		if (is_array($group['member'])) {
893
			$index = array_search($user['uid'], $group['member']);
894
			array_splice($group['member'], $index, 1);
895
			$mod_groups[] = $group;
896
		}
897
	}
898
	unset($group);
899

    
900
	/* sync all modified groups */
901
	foreach ($mod_groups as $group) {
902
		local_group_set($group);
903
	}
904
}
905

    
906
function local_group_del_user($user) {
907
	global $config;
908

    
909
	if (!is_array($config['system']['group'])) {
910
		return;
911
	}
912

    
913
	foreach ($config['system']['group'] as $group) {
914
		if (is_array($group['member'])) {
915
			foreach ($group['member'] as $idx => $uid) {
916
				if ($user['uid'] == $uid) {
917
					unset($config['system']['group']['member'][$idx]);
918
				}
919
			}
920
		}
921
	}
922
}
923

    
924
function local_group_set($group, $reset = false) {
925
	global $debug;
926

    
927
	$group_name = $group['name'];
928
	$group_gid = $group['gid'];
929
	$group_members = '';
930

    
931
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
932
		$group_members = implode(",", $group['member']);
933
	}
934

    
935
	if (empty($group_name)) {
936
		return;
937
	}
938

    
939
	// If the group is now remote, make sure there is no local group with the same name
940
	if ($group['scope'] == "remote") {
941
		local_group_del($group);
942
		return;
943
	}
944

    
945
	/* determine add or mod */
946
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
947
		$group_op = "groupmod -l";
948
	} else {
949
		$group_op = "groupadd -n";
950
	}
951

    
952
	/* add or mod group db */
953
	$cmd = "/usr/sbin/pw {$group_op} " .
954
		escapeshellarg($group_name) .
955
		" -g " . escapeshellarg($group_gid) .
956
		" -M " . escapeshellarg($group_members) . " 2>&1";
957

    
958
	if ($debug) {
959
		log_error(sprintf(gettext("Running: %s"), $cmd));
960
	}
961

    
962
	mwexec($cmd);
963
}
964

    
965
function local_group_del($group) {
966
	global $debug;
967

    
968
	/* delete from group db */
969
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
970

    
971
	if ($debug) {
972
		log_error(sprintf(gettext("Running: %s"), $cmd));
973
	}
974
	mwexec($cmd);
975
}
976

    
977
function ldap_test_connection($authcfg) {
978
	if ($authcfg) {
979
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
980
			$ldapproto = "ldaps";
981
		} else {
982
			$ldapproto = "ldap";
983
		}
984
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
985
		$ldapport = $authcfg['ldap_port'];
986
		if (!empty($ldapport)) {
987
			$ldapserver .= ":{$ldapport}";
988
		}
989
	} else {
990
		return false;
991
	}
992

    
993
	/* first check if there is even an LDAP server populated */
994
	if (!$ldapserver) {
995
		return false;
996
	}
997

    
998
	/* connect and see if server is up */
999
	$error = false;
1000
	if (!($ldap = ldap_connect($ldapserver))) {
1001
		$error = true;
1002
	}
1003

    
1004
	if ($error == true) {
1005
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
1006
		return false;
1007
	}
1008

    
1009
	/* Setup CA environment if needed. */
1010
	ldap_setup_caenv($ldap, $authcfg);
1011

    
1012
	return true;
1013
}
1014

    
1015
function ldap_setup_caenv($ldap, $authcfg) {
1016
	global $g;
1017
	require_once("certs.inc");
1018

    
1019
	unset($caref);
1020
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
1021
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
1022
		return;
1023
	} elseif ($authcfg['ldap_caref'] == "global") {
1024
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, "/etc/ssl/");
1025
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, "/etc/ssl/cert.pem");
1026
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1027
	} else {
1028
		$caref = lookup_ca($authcfg['ldap_caref']);
1029
		$cert_details = openssl_x509_parse(base64_decode($caref['crt']));
1030
		$param = array('caref' => $authcfg['ldap_caref']);
1031
		$cachain = ca_chain($param);
1032
		if (!$caref) {
1033
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
1034
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
1035
			ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1036
			return;
1037
		}
1038

    
1039
		$cert_path = "{$g['varrun_path']}/certs";
1040
		$cert_filename = "{$cert_path}/{$cert_details['hash']}.0";
1041
		safe_mkdir($cert_path);
1042
		unlink_if_exists($cert_filename);
1043
		file_put_contents($cert_filename, $cachain);
1044
		@chmod($cert_filename, 0600);
1045

    
1046
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1047
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, $cert_path);
1048
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, $cert_filename);
1049
	}
1050
}
1051

    
1052
function ldap_test_bind($authcfg) {
1053
	global $debug, $config, $g;
1054

    
1055
	if ($authcfg) {
1056
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1057
			$ldapproto = "ldaps";
1058
		} else {
1059
			$ldapproto = "ldap";
1060
		}
1061
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1062
		$ldapport = $authcfg['ldap_port'];
1063
		if (!empty($ldapport)) {
1064
			$ldapserver .= ":{$ldapport}";
1065
		}
1066
		$ldapbasedn = $authcfg['ldap_basedn'];
1067
		$ldapbindun = $authcfg['ldap_binddn'];
1068
		$ldapbindpw = $authcfg['ldap_bindpw'];
1069
		$ldapver = $authcfg['ldap_protver'];
1070
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1071
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1072
			$ldapanon = true;
1073
		} else {
1074
			$ldapanon = false;
1075
		}
1076
	} else {
1077
		return false;
1078
	}
1079

    
1080
	/* first check if there is even an LDAP server populated */
1081
	if (!$ldapserver) {
1082
		return false;
1083
	}
1084

    
1085
	/* connect and see if server is up */
1086
	$error = false;
1087
	if (!($ldap = ldap_connect($ldapserver))) {
1088
		$error = true;
1089
	}
1090

    
1091
	if ($error == true) {
1092
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1093
		return false;
1094
	}
1095

    
1096
	/* Setup CA environment if needed. */
1097
	ldap_setup_caenv($ldap, $authcfg);
1098

    
1099
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1100
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1101
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1102
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1103
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1104

    
1105
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1106
		if (!(@ldap_start_tls($ldap))) {
1107
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1108
			@ldap_close($ldap);
1109
			return false;
1110
		}
1111
	}
1112

    
1113
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1114
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1115
	if ($ldapanon == true) {
1116
		if (!($res = @ldap_bind($ldap))) {
1117
			@ldap_close($ldap);
1118
			return false;
1119
		}
1120
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1121
		@ldap_close($ldap);
1122
		return false;
1123
	}
1124

    
1125
	@ldap_unbind($ldap);
1126

    
1127
	return true;
1128
}
1129

    
1130
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1131
	global $debug, $config, $g;
1132

    
1133
	if (!function_exists("ldap_connect")) {
1134
		return;
1135
	}
1136

    
1137
	$ous = array();
1138

    
1139
	if ($authcfg) {
1140
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1141
			$ldapproto = "ldaps";
1142
		} else {
1143
			$ldapproto = "ldap";
1144
		}
1145
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1146
		$ldapport = $authcfg['ldap_port'];
1147
		if (!empty($ldapport)) {
1148
			$ldapserver .= ":{$ldapport}";
1149
		}
1150
		$ldapbasedn = $authcfg['ldap_basedn'];
1151
		$ldapbindun = $authcfg['ldap_binddn'];
1152
		$ldapbindpw = $authcfg['ldap_bindpw'];
1153
		$ldapver = $authcfg['ldap_protver'];
1154
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1155
			$ldapanon = true;
1156
		} else {
1157
			$ldapanon = false;
1158
		}
1159
		$ldapname = $authcfg['name'];
1160
		$ldapfallback = false;
1161
		$ldapscope = $authcfg['ldap_scope'];
1162
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1163
	} else {
1164
		return false;
1165
	}
1166

    
1167
	/* first check if there is even an LDAP server populated */
1168
	if (!$ldapserver) {
1169
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1170
		return $ous;
1171
	}
1172

    
1173
	/* connect and see if server is up */
1174
	$error = false;
1175
	if (!($ldap = ldap_connect($ldapserver))) {
1176
		$error = true;
1177
	}
1178

    
1179
	if ($error == true) {
1180
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1181
		return $ous;
1182
	}
1183

    
1184
	/* Setup CA environment if needed. */
1185
	ldap_setup_caenv($ldap, $authcfg);
1186

    
1187
	$ldapfilter = "(|(ou=*)(cn=Users))";
1188

    
1189
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1190
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1191
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1192
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1193
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1194

    
1195
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1196
		if (!(@ldap_start_tls($ldap))) {
1197
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1198
			@ldap_close($ldap);
1199
			return false;
1200
		}
1201
	}
1202

    
1203
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1204
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1205
	if ($ldapanon == true) {
1206
		if (!($res = @ldap_bind($ldap))) {
1207
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1208
			@ldap_close($ldap);
1209
			return $ous;
1210
		}
1211
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1212
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1213
		@ldap_close($ldap);
1214
		return $ous;
1215
	}
1216

    
1217
	if ($ldapscope == "one") {
1218
		$ldapfunc = "ldap_list";
1219
	} else {
1220
		$ldapfunc = "ldap_search";
1221
	}
1222

    
1223
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1224
	$info = @ldap_get_entries($ldap, $search);
1225

    
1226
	if (is_array($info)) {
1227
		foreach ($info as $inf) {
1228
			if (!$show_complete_ou) {
1229
				$inf_split = explode(",", $inf['dn']);
1230
				$ou = $inf_split[0];
1231
				$ou = str_replace("OU=", "", $ou);
1232
				$ou = str_replace("CN=", "", $ou);
1233
			} else {
1234
				if ($inf['dn']) {
1235
					$ou = $inf['dn'];
1236
				}
1237
			}
1238
			if ($ou) {
1239
				$ous[] = $ou;
1240
			}
1241
		}
1242
	}
1243

    
1244
	@ldap_unbind($ldap);
1245

    
1246
	return $ous;
1247
}
1248

    
1249
function ldap_get_groups($username, $authcfg) {
1250
	global $debug, $config;
1251

    
1252
	if (!function_exists("ldap_connect")) {
1253
		return array();
1254
	}
1255

    
1256
	if (!$username) {
1257
		return array();
1258
	}
1259

    
1260
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1261
		$username_split = explode("@", $username);
1262
		$username = $username_split[0];
1263
	}
1264

    
1265
	if (stristr($username, "\\")) {
1266
		$username_split = explode("\\", $username);
1267
		$username = $username_split[0];
1268
	}
1269

    
1270
	//log_error("Getting LDAP groups for {$username}.");
1271
	if ($authcfg) {
1272
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1273
			$ldapproto = "ldaps";
1274
		} else {
1275
			$ldapproto = "ldap";
1276
		}
1277
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1278
		$ldapport = $authcfg['ldap_port'];
1279
		if (!empty($ldapport)) {
1280
			$ldapserver .= ":{$ldapport}";
1281
		}
1282
		$ldapbasedn = $authcfg['ldap_basedn'];
1283
		$ldapbindun = $authcfg['ldap_binddn'];
1284
		$ldapbindpw = $authcfg['ldap_bindpw'];
1285
		$ldapauthcont = $authcfg['ldap_authcn'];
1286
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1287
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1288
		$ldaptype = "";
1289
		$ldapver = $authcfg['ldap_protver'];
1290
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1291
			$ldapanon = true;
1292
		} else {
1293
			$ldapanon = false;
1294
		}
1295
		$ldapname = $authcfg['name'];
1296
		$ldapfallback = false;
1297
		$ldapscope = $authcfg['ldap_scope'];
1298
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1299
	} else {
1300
		return array();
1301
	}
1302

    
1303
	if (isset($authcfg['ldap_rfc2307'])) {
1304
		$ldapdn = $ldapbasedn;
1305
	} else {
1306
		$ldapdn = $_SESSION['ldapdn'];
1307
	}
1308

    
1309
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1310
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1311
	$memberof = array();
1312

    
1313
	/* connect and see if server is up */
1314
	$error = false;
1315
	if (!($ldap = ldap_connect($ldapserver))) {
1316
		$error = true;
1317
	}
1318

    
1319
	if ($error == true) {
1320
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1321
		return $memberof;
1322
	}
1323

    
1324
	/* Setup CA environment if needed. */
1325
	ldap_setup_caenv($ldap, $authcfg);
1326

    
1327
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1328
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1329
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1330
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1331
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1332

    
1333
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1334
		if (!(@ldap_start_tls($ldap))) {
1335
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1336
			@ldap_close($ldap);
1337
			return array();
1338
		}
1339
	}
1340

    
1341
	/* bind as user that has rights to read group attributes */
1342
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1343
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1344
	if ($ldapanon == true) {
1345
		if (!($res = @ldap_bind($ldap))) {
1346
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1347
			@ldap_close($ldap);
1348
			return array();
1349
		}
1350
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1351
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1352
		@ldap_close($ldap);
1353
		return $memberof;
1354
	}
1355

    
1356
	/* get groups from DN found */
1357
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1358
	/* since we know the DN is in $_SESSION['ldapdn'] */
1359
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1360
	if ($ldapscope == "one") {
1361
		$ldapfunc = "ldap_list";
1362
	} else {
1363
		$ldapfunc = "ldap_search";
1364
	}
1365

    
1366
	if (isset($authcfg['ldap_rfc2307'])) {
1367
		if (isset($authcfg['ldap_rfc2307_userdn'])) {
1368
			$ldac_splits = explode(";", $ldapauthcont);
1369
			foreach ($ldac_splits as $i => $ldac_split) {
1370
				$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1371
				$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1372
				$ldapfilter = "({$ldapnameattribute}={$username})";
1373
				if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1374
					$ldapdn = $ldac_split;
1375
				} else {
1376
					$ldapdn = $ldapsearchbasedn;
1377
				}
1378
				$usersearch = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1379
				$userinfo = @ldap_get_entries($ldap, $usersearch);
1380
			}
1381
			$username = $userinfo[0]['dn'];
1382
		}
1383
		$ldapfilter = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1384
	} else {
1385
		$ldapfilter = "({$ldapnameattribute}={$username})";
1386
	}
1387

    
1388
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1389
	$info = @ldap_get_entries($ldap, $search);
1390

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

    
1393
	if (is_array($gresults)) {
1394
		/* Iterate through the groups and throw them into an array */
1395
		foreach ($gresults as $grp) {
1396
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1397
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1398
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1399
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1400
			}
1401
		}
1402
	}
1403

    
1404
	/* Time to close LDAP connection */
1405
	@ldap_unbind($ldap);
1406

    
1407
	$groups = print_r($memberof, true);
1408

    
1409
	//log_error("Returning groups ".$groups." for user $username");
1410

    
1411
	return $memberof;
1412
}
1413

    
1414
function ldap_format_host($host) {
1415
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1416
}
1417

    
1418
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1419
	global $debug, $config;
1420

    
1421
	if (!$username) {
1422
		$attributes['error_message'] = gettext("Invalid Login.");
1423
		return false;
1424
	}
1425

    
1426
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1427
		$attributes['error_message'] = gettext("Invalid credentials.");
1428
		return false;
1429
	}
1430

    
1431
	if (!function_exists("ldap_connect")) {
1432
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1433
		$attributes['error_message'] = gettext("Internal error during authentication.");
1434
		return null;
1435
	}
1436

    
1437
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1438
		$username_split = explode("@", $username);
1439
		$username = $username_split[0];
1440
	}
1441
	if (stristr($username, "\\")) {
1442
		$username_split = explode("\\", $username);
1443
		$username = $username_split[0];
1444
	}
1445

    
1446
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1447

    
1448
	if ($authcfg) {
1449
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1450
			$ldapproto = "ldaps";
1451
		} else {
1452
			$ldapproto = "ldap";
1453
		}
1454
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1455
		$ldapport = $authcfg['ldap_port'];
1456
		if (!empty($ldapport)) {
1457
			$ldapserver .= ":{$ldapport}";
1458
		}
1459
		$ldapbasedn = $authcfg['ldap_basedn'];
1460
		$ldapbindun = $authcfg['ldap_binddn'];
1461
		$ldapbindpw = $authcfg['ldap_bindpw'];
1462
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1463
			$ldapanon = true;
1464
		} else {
1465
			$ldapanon = false;
1466
		}
1467
		$ldapauthcont = $authcfg['ldap_authcn'];
1468
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1469
		$ldapgroupattribute = $authcfg['ldap_attr_member'];
1470
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1471
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1472
		$ldapfilter = "";
1473
		if (!$ldapextendedqueryenabled) {
1474
			$ldapfilter = "({$ldapnameattribute}={$username})";
1475
		} else {
1476
			if (isset($authcfg['ldap_rfc2307'])) {
1477
				$ldapfilter = "({$ldapnameattribute}={$username})";
1478
				$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1479
			} else {
1480
				$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1481
			}
1482
		}
1483
		$ldaptype = "";
1484
		$ldapver = $authcfg['ldap_protver'];
1485
		$ldapname = $authcfg['name'];
1486
		$ldapscope = $authcfg['ldap_scope'];
1487
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1488
	} else {
1489
		return null;
1490
	}
1491

    
1492
	/* first check if there is even an LDAP server populated */
1493
	if (!$ldapserver) {
1494
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1495
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1496
		return null;
1497
	}
1498

    
1499
	/* Make sure we can connect to LDAP */
1500
	$error = false;
1501
	if (!($ldap = ldap_connect($ldapserver))) {
1502
		$error = true;
1503
	}
1504

    
1505
	/* Setup CA environment if needed. */
1506
	ldap_setup_caenv($ldap, $authcfg);
1507

    
1508
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1509
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1510
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1511
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1512
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1513

    
1514
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1515
		if (!(@ldap_start_tls($ldap))) {
1516
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1517
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1518
			@ldap_close($ldap);
1519
			return null;
1520
		}
1521
	}
1522

    
1523
	if ($error == true) {
1524
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1525
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1526
		return null;
1527
	}
1528

    
1529
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1530
	$error = false;
1531
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1532
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1533
	if ($ldapanon == true) {
1534
		if (!($res = @ldap_bind($ldap))) {
1535
			$error = true;
1536
		}
1537
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1538
		$error = true;
1539
	}
1540

    
1541
	if ($error == true) {
1542
		@ldap_close($ldap);
1543
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1544
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1545
		return null;
1546
	}
1547

    
1548
	/* Get LDAP Authcontainers and split em up. */
1549
	$ldac_splits = explode(";", $ldapauthcont);
1550

    
1551
	/* setup the usercount so we think we haven't found anyone yet */
1552
	$usercount = 0;
1553

    
1554
	/*****************************************************************/
1555
	/*  We first find the user based on username and filter          */
1556
	/*  then, once we find the first occurrence of that person       */
1557
	/*  we set session variables to point to the OU and DN of the    */
1558
	/*  person.  To later be used by ldap_get_groups.                */
1559
	/*  that way we don't have to search twice.                      */
1560
	/*****************************************************************/
1561
	if ($debug) {
1562
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1563
	}
1564
	/* Iterate through the user containers for search */
1565
	foreach ($ldac_splits as $i => $ldac_split) {
1566
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1567
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1568
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1569
		/* Make sure we just use the first user we find */
1570
		if ($debug) {
1571
			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)));
1572
		}
1573
		if ($ldapscope == "one") {
1574
			$ldapfunc = "ldap_list";
1575
		} else {
1576
			$ldapfunc = "ldap_search";
1577
		}
1578
		/* Support legacy auth container specification. */
1579
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1580
			$ldapdn = $ldac_split;
1581
		} else {
1582
			$ldapdn = $ldapsearchbasedn;
1583
		}
1584
		$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1585
		if (!$search) {
1586
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1587
			continue;
1588
		}
1589
		if (isset($authcfg['ldap_rfc2307']) && isset($ldapgroupfilter)) {
1590
			if (isset($authcfg['ldap_rfc2307_userdn'])) {
1591
				$info = ldap_get_entries($ldap, $search);
1592
				$username = $info[0]['dn'];
1593
			}
1594
			$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1595
			$groupsearch = @$ldapfunc($ldap, $ldapdn, $ldapgroupfilter);
1596
		}
1597

    
1598
		if (isset($ldapgroupfilter) && !$groupsearch) {
1599
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1600
			continue;
1601
		}
1602
		if (isset($groupsearch)) {
1603
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1604
			if ($debug) {
1605
				log_auth(sprintf(gettext("LDAP group search: %s results."), $validgroup));
1606
			}
1607
		}
1608
		$info = ldap_get_entries($ldap, $search);
1609
		$matches = $info['count'];
1610
		if ($matches == 1) {
1611
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1612
			$_SESSION['ldapou'] = $ldac_split[$i];
1613
			$_SESSION['ldapon'] = "true";
1614
			$usercount = 1;
1615
			break;
1616
		}
1617
	}
1618

    
1619
	if ($usercount != 1) {
1620
		@ldap_unbind($ldap);
1621
		if ($debug) {
1622
			if ($usercount === 0) {
1623
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1624
			} else {
1625
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1626
			}
1627
		}
1628
		$attributes['error_message'] = gettext("Invalid login specified.");
1629
		return false;
1630
	}
1631

    
1632
	/* Now lets bind as the user we found */
1633
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1634
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1635
		if ($debug) {
1636
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1637
		}
1638
		@ldap_unbind($ldap);
1639
		return false;
1640
	}
1641

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

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

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

    
1654
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1655
		return false;
1656
	}
1657

    
1658
	return true;
1659
}
1660

    
1661
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1662
	global $debug, $config;
1663
	$ret = false;
1664

    
1665
	require_once("Auth/RADIUS.php");
1666
	require_once("Crypt/CHAP.php");
1667

    
1668
	if ($authcfg) {
1669
		$radiusservers = array();
1670
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1671
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1672
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1673
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1674
		if(isset($authcfg['radius_protocol'])) {
1675
			$radius_protocol = $authcfg['radius_protocol'];
1676
		} else {
1677
			$radius_protocol = 'PAP';
1678
		}
1679
	} else {
1680
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1681
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1682
		return null;
1683
	}
1684

    
1685
	// Create our instance
1686
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1687
	$rauth = new $classname($username, $password);
1688

    
1689
	/* Add new servers to our instance */
1690
	foreach ($radiusservers as $radsrv) {
1691
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1692
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1693
	}
1694

    
1695
	// Construct data package
1696
	$rauth->username = $username;
1697
	switch ($radius_protocol) {
1698
		case 'CHAP_MD5':
1699
		case 'MSCHAPv1':
1700
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1701
			$crpt = new $classname;
1702
			$crpt->username = $username;
1703
			$crpt->password = $password;
1704
			$rauth->challenge = $crpt->challenge;
1705
			$rauth->chapid = $crpt->chapid;
1706
			$rauth->response = $crpt->challengeResponse();
1707
			$rauth->flags = 1;
1708
			break;
1709

    
1710
		case 'MSCHAPv2':
1711
			$crpt = new Crypt_CHAP_MSv2;
1712
			$crpt->username = $username;
1713
			$crpt->password = $password;
1714
			$rauth->challenge = $crpt->authChallenge;
1715
			$rauth->peerChallenge = $crpt->peerChallenge;
1716
			$rauth->chapid = $crpt->chapid;
1717
			$rauth->response = $crpt->challengeResponse();
1718
			break;
1719

    
1720
		default:
1721
			$rauth->password = $password;
1722
			break;
1723
	}
1724

    
1725
	if (PEAR::isError($rauth->start())) {
1726
		$ret = null;
1727
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1728
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1729
	} else {
1730
		$nasid = $attributes['nas_identifier'];
1731
		$nasip = $authcfg['radius_nasip_attribute'];
1732
		if (empty($nasid)) {
1733
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1734
		}
1735
		if (!is_ipaddr($nasip)) {
1736
			$nasip = get_interface_ip($nasip);
1737

    
1738
			if (!is_ipaddr($nasip)) {
1739
				/* use first interface with IP as fallback for NAS-IP-Address
1740
				 * see https://redmine.pfsense.org/issues/11109 */
1741
				foreach (get_configured_interface_list() as $if) {
1742
					$nasip = get_interface_ip($if);
1743
					if (is_ipaddr($nasip)) {
1744
						break;
1745
					}
1746
				}
1747
			}
1748
		}
1749
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1750

    
1751
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1752
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1753

    
1754
		if(!empty($attributes['calling_station_id'])) {
1755
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1756
		}
1757
		// Carefully check that interface has a MAC address
1758
		if(!empty($nasmac)) {
1759
			$nasmac = mac_format($nasmac);
1760
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1761
		}
1762
		if(!empty($attributes['nas_port_type'])) {
1763
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1764
		}
1765
		if(!empty($attributes['nas_port'])) {
1766
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1767
		}
1768
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1769
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1770
		}
1771
	}
1772

    
1773
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1774

    
1775
	/* Send request */
1776
	$result = $rauth->send();
1777
	if (PEAR::isError($result)) {
1778
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1779
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1780
		$ret = null;
1781
	} else if ($result === true) {
1782
		$ret = true;
1783
	} else {
1784
		$ret = false;
1785
	}
1786

    
1787

    
1788
	// Get attributes, even if auth failed.
1789
	if ($rauth->getAttributes()) {
1790
	$attributes = array_merge($attributes,$rauth->listAttributes());
1791

    
1792
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1793
	if (!empty($attributes['session_terminate_time'])) {
1794
			$stt = &$attributes['session_terminate_time'];
1795
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1796
		}
1797
	}
1798

    
1799
	// close OO RADIUS_AUTHENTICATION
1800
	$rauth->close();
1801

    
1802
	return $ret;
1803
}
1804

    
1805
/*
1806
	$attributes must contain a "class" key containing the groups and local
1807
	groups must exist to match.
1808
*/
1809
function radius_get_groups($attributes) {
1810
	$groups = array();
1811
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1812
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1813
		$groups = array();
1814
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1815
			foreach ($attributes['class'] as $class) {
1816
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1817
			}
1818
		}
1819

    
1820
		foreach ($groups as & $grp) {
1821
			$grp = trim($grp);
1822
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1823
				$grp = substr($grp, 3);
1824
			}
1825
		}
1826
	}
1827
	return $groups;
1828
}
1829

    
1830
function get_user_expiration_date($username) {
1831
	$user = getUserEntry($username);
1832
	if ($user['expires']) {
1833
		return $user['expires'];
1834
	}
1835
}
1836

    
1837
function is_account_expired($username) {
1838
	$expirydate = get_user_expiration_date($username);
1839
	if ($expirydate) {
1840
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1841
			return true;
1842
		}
1843
	}
1844

    
1845
	return false;
1846
}
1847

    
1848
function is_account_disabled($username) {
1849
	$user = getUserEntry($username);
1850
	if (isset($user['disabled'])) {
1851
		return true;
1852
	}
1853

    
1854
	return false;
1855
}
1856

    
1857
function get_user_settings($username) {
1858
	global $config;
1859
	$settings = array();
1860
	$settings['widgets'] = $config['widgets'];
1861
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1862
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1863
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1864
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1865
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1866
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1867
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1868
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1869
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1870
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1871
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1872
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1873
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1874
	$user = getUserEntry($username);
1875
	if (isset($user['customsettings'])) {
1876
		$settings['customsettings'] = true;
1877
		if (isset($user['widgets'])) {
1878
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1879
			$settings['widgets'] = $user['widgets'];
1880
		}
1881
		if (isset($user['dashboardcolumns'])) {
1882
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1883
		}
1884
		if (isset($user['webguicss'])) {
1885
			$settings['webgui']['webguicss'] = $user['webguicss'];
1886
		}
1887
		if (isset($user['webguihostnamemenu'])) {
1888
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1889
		}
1890
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1891
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1892
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1893
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1894
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1895
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1896
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1897
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1898
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1899
	} else {
1900
		$settings['customsettings'] = false;
1901
	}
1902

    
1903
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1904
		$settings['webgui']['dashboardcolumns'] = 2;
1905
	}
1906

    
1907
	return $settings;
1908
}
1909

    
1910
function save_widget_settings($username, $settings, $message = "") {
1911
	global $config, $userindex;
1912
	$user = getUserEntry($username);
1913

    
1914
	if (strlen($message) > 0) {
1915
		$msgout = $message;
1916
	} else {
1917
		$msgout = gettext("Widget configuration has been changed.");
1918
	}
1919

    
1920
	if (isset($user['customsettings'])) {
1921
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1922
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1923
	} else {
1924
		$config['widgets'] = $settings;
1925
		write_config($msgout);
1926
	}
1927
}
1928

    
1929
function auth_get_authserver($name) {
1930
	global $config;
1931

    
1932
	if (is_array($config['system']['authserver'])) {
1933
		foreach ($config['system']['authserver'] as $authcfg) {
1934
			if ($authcfg['name'] == $name) {
1935
				return $authcfg;
1936
			}
1937
		}
1938
	}
1939
	if ($name == "Local Database") {
1940
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1941
	}
1942
}
1943

    
1944
function auth_get_authserver_list() {
1945
	global $config;
1946

    
1947
	$list = array();
1948

    
1949
	if (is_array($config['system']['authserver'])) {
1950
		foreach ($config['system']['authserver'] as $authcfg) {
1951
			/* Add support for disabled entries? */
1952
			$list[$authcfg['name']] = $authcfg;
1953
		}
1954
	}
1955

    
1956
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1957
	return $list;
1958
}
1959

    
1960
function getUserGroups($username, $authcfg, &$attributes = array()) {
1961
	global $config;
1962

    
1963
	$allowed_groups = array();
1964

    
1965
	switch ($authcfg['type']) {
1966
		case 'ldap':
1967
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1968
			break;
1969
		case 'radius':
1970
			$allowed_groups = @radius_get_groups($attributes);
1971
			break;
1972
		default:
1973
			$user = getUserEntry($username);
1974
			$allowed_groups = @local_user_get_groups($user, true);
1975
			break;
1976
	}
1977

    
1978
	$member_groups = array();
1979
	if (is_array($config['system']['group'])) {
1980
		foreach ($config['system']['group'] as $group) {
1981
			if (in_array($group['name'], $allowed_groups)) {
1982
				$member_groups[] = $group['name'];
1983
			}
1984
		}
1985
	}
1986

    
1987
	return $member_groups;
1988
}
1989

    
1990
/*
1991
Possible return values :
1992
true : authentication worked
1993
false : authentication failed (invalid login/password, not enough permission, etc...)
1994
null : error during authentication process (unable to reach remote server, etc...)
1995
*/
1996
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1997

    
1998
	if (is_array($username) || is_array($password)) {
1999
		return false;
2000
	}
2001

    
2002
	if (!$authcfg) {
2003
		return local_backed($username, $password, $attributes);
2004
	}
2005

    
2006
	$authenticated = false;
2007
	switch ($authcfg['type']) {
2008
		case 'ldap':
2009
			try {
2010
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
2011
			} catch (Exception $e) {
2012
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
2013
			}
2014
			break;
2015

    
2016
			break;
2017
		case 'radius':
2018
			try {
2019
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
2020
			} catch (Exception $e) {
2021
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
2022
			}
2023
			break;
2024
		default:
2025
			/* lookup user object by name */
2026
			try {
2027
				$authenticated = local_backed($username, $password, $attributes);
2028
			} catch (Exception $e) {
2029
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
2030
			}
2031
			break;
2032
		}
2033

    
2034
	return $authenticated;
2035
}
2036

    
2037
function session_auth() {
2038
	global $config, $_SESSION, $page;
2039

    
2040
	// Handle HTTPS httponly and secure flags
2041
	$currentCookieParams = session_get_cookie_params();
2042
	session_set_cookie_params(
2043
		$currentCookieParams["lifetime"],
2044
		$currentCookieParams["path"],
2045
		NULL,
2046
		($config['system']['webgui']['protocol'] == "https"),
2047
		true
2048
	);
2049

    
2050
	phpsession_begin();
2051

    
2052
	// Detect protocol change
2053
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2054
		phpsession_end();
2055
		return false;
2056
	}
2057

    
2058
	/* Validate incoming login request */
2059
	$attributes = array('nas_identifier' => 'webConfigurator-' . gethostname());
2060
	if (isset($_POST['login']) && !empty($_POST['usernamefld'])) {
2061
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2062
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
2063
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
2064
			// Generate a new id to avoid session fixation
2065
			session_regenerate_id();
2066
			$_SESSION['Logged_In'] = "True";
2067
			$_SESSION['remoteauth'] = $remoteauth;
2068
			if ($remoteauth) {
2069
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
2070
					$_SESSION['authsource'] = "Local Database";
2071
				} else {
2072
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
2073
				}
2074
			} else {
2075
				$_SESSION['authsource'] = 'Local Database Fallback';
2076
			}
2077
			$_SESSION['Username'] = $_POST['usernamefld'];
2078
			$_SESSION['user_radius_attributes'] = $attributes;
2079
			$_SESSION['last_access'] = time();
2080
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
2081
			phpsession_end(true);
2082
			if (!isset($config['system']['webgui']['quietlogin'])) {
2083
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2084
			}
2085
			if (isset($_POST['postafterlogin'])) {
2086
				return true;
2087
			} else {
2088
				if (empty($page)) {
2089
					$page = "/";
2090
				}
2091
				header("Location: {$page}");
2092
			}
2093
			exit;
2094
		} else {
2095
			/* give the user an error message */
2096
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
2097
			log_auth(sprintf(gettext("webConfigurator authentication error for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2098
			if (isAjax()) {
2099
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
2100
				return;
2101
			}
2102
		}
2103
	}
2104

    
2105
	/* Show login page if they aren't logged in */
2106
	if (empty($_SESSION['Logged_In'])) {
2107
		phpsession_end(true);
2108
		return false;
2109
	}
2110

    
2111
	/* If session timeout isn't set, we don't mark sessions stale */
2112
	if (!isset($config['system']['webgui']['session_timeout'])) {
2113
		/* Default to 4 hour timeout if one is not set */
2114
		if ($_SESSION['last_access'] < (time() - 14400)) {
2115
			$_POST['logout'] = true;
2116
			$_SESSION['Logout'] = true;
2117
		} else {
2118
			$_SESSION['last_access'] = time();
2119
		}
2120
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2121
		/* only update if it wasn't ajax */
2122
		if (!isAjax()) {
2123
			$_SESSION['last_access'] = time();
2124
		}
2125
	} else {
2126
		/* Check for stale session */
2127
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2128
			$_POST['logout'] = true;
2129
			$_SESSION['Logout'] = true;
2130
		} else {
2131
			/* only update if it wasn't ajax */
2132
			if (!isAjax()) {
2133
				$_SESSION['last_access'] = time();
2134
			}
2135
		}
2136
	}
2137

    
2138
	/* user hit the logout button */
2139
	if (isset($_POST['logout'])) {
2140

    
2141
		if ($_SESSION['Logout']) {
2142
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2143
		} else {
2144
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2145
		}
2146

    
2147
		/* wipe out $_SESSION */
2148
		$_SESSION = array();
2149

    
2150
		if (isset($_COOKIE[session_name()])) {
2151
			setcookie(session_name(), '', time()-42000, '/');
2152
		}
2153

    
2154
		/* and destroy it */
2155
		phpsession_destroy();
2156

    
2157
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2158
		$scriptElms = count($scriptName);
2159
		$scriptName = $scriptName[$scriptElms-1];
2160

    
2161
		if (isAjax()) {
2162
			return false;
2163
		}
2164

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

    
2168
		return false;
2169
	}
2170

    
2171
	/*
2172
	 * this is for debugging purpose if you do not want to use Ajax
2173
	 * to submit a HTML form. It basically disables the observation
2174
	 * of the submit event and hence does not trigger Ajax.
2175
	 */
2176
	if ($_REQUEST['disable_ajax']) {
2177
		$_SESSION['NO_AJAX'] = "True";
2178
	}
2179

    
2180
	/*
2181
	 * Same to re-enable Ajax.
2182
	 */
2183
	if ($_REQUEST['enable_ajax']) {
2184
		unset($_SESSION['NO_AJAX']);
2185
	}
2186
	phpsession_end(true);
2187
	return true;
2188
}
2189

    
2190
function print_credit() {
2191
	global $g;
2192

    
2193
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_label"] . '</a>' .
2194
			gettext(' is developed and maintained by ') .
2195
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2196
			'<a target="_blank" href="https://pfsense.org/license">' .
2197
			gettext(' View license.') . '</a>';
2198
}
2199
function get_user_remote_address() {
2200
	$remote_address = $_SERVER['REMOTE_ADDR'];
2201
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2202
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2203
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2204
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2205
	}
2206
	return $remote_address;
2207
}
2208
function get_user_remote_authsource() {
2209
	$authsource = "";
2210
	if (!empty($_SESSION['authsource'])) {
2211
		$authsource .= " ({$_SESSION['authsource']})";
2212
	}
2213
	return $authsource;
2214
}
2215

    
2216
function set_pam_auth() {
2217
	global $config;
2218

    
2219
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2220

    
2221
	unlink_if_exists("/etc/radius.conf");
2222
	unlink_if_exists("/var/etc/pam_ldap.conf");
2223
	unlink_if_exists("/var/etc/pam_ldap_ca.crt");
2224

    
2225
	$header = "# This file is automatically generated. Do not edit.\n\n";
2226
	$pam_sshd =<<<EOD
2227
# auth
2228
auth		required	pam_unix.so		no_warn try_first_pass
2229

    
2230
# account
2231
account		required	pam_nologin.so
2232
account		required	pam_login_access.so
2233
account		required	pam_unix.so
2234

    
2235
# session
2236
session		required	pam_permit.so
2237

    
2238
# password
2239
password	required	pam_unix.so		no_warn try_first_pass
2240

    
2241
EOD;
2242

    
2243
	$pam_system =<<<EOD
2244
# auth
2245
auth		required	pam_unix.so		no_warn try_first_pass
2246

    
2247
# account
2248
account		required	pam_login_access.so
2249
account		required	pam_unix.so
2250

    
2251
# session
2252
session		required	pam_lastlog.so		no_fail
2253

    
2254
# password
2255
password	required	pam_unix.so		no_warn try_first_pass
2256

    
2257
EOD;
2258

    
2259
	$nsswitch =<<<EOD
2260
group: files
2261
hosts: files dns
2262
netgroup: files
2263
networks: files
2264
passwd: files
2265
shells: files
2266
services: files
2267
protocols: files
2268
rpc: files
2269

    
2270
EOD;
2271

    
2272
	if (isset($config['system']['webgui']['shellauth'])) {
2273
		if (($authcfg['type'] == "radius") && isset($authcfg['radius_auth_port'])) {
2274
			$radius_conf = "auth {$authcfg['host']}:{$authcfg['radius_auth_port']} " .
2275
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2276
			if (isset($authcfg['radius_acct_port'])) {
2277
				$radius_conf .= "acct {$authcfg['host']}:{$authcfg['radius_acct_port']} " .
2278
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2279
			}
2280
			
2281
			$pam_sshd =<<<EOD
2282
# auth
2283
auth            sufficient      pam_radius.so
2284
auth		required	pam_unix.so		no_warn try_first_pass
2285

    
2286
# account
2287
account		required	pam_nologin.so
2288
account		required	pam_login_access.so
2289
account         sufficient      pam_radius.so
2290

    
2291
# session
2292
session		required	pam_permit.so
2293

    
2294
# password
2295
password        sufficient      pam_radius.so
2296
password	required	pam_unix.so		no_warn try_first_pass
2297

    
2298
EOD;
2299

    
2300
			$pam_system =<<<EOD
2301
# auth
2302
auth            sufficient      pam_radius.so
2303
auth		required	pam_unix.so		no_warn try_first_pass
2304

    
2305
# account
2306
account		required	pam_login_access.so
2307
account         sufficient      pam_radius.so
2308

    
2309
# session
2310
session		required	pam_lastlog.so		no_fail
2311

    
2312
# password
2313
password        sufficient      pam_radius.so
2314
password	required	pam_unix.so		no_warn try_first_pass
2315

    
2316
EOD;
2317

    
2318
			@file_put_contents("/etc/radius.conf", $header . $radius_conf);
2319
		} elseif (($authcfg['type'] == "ldap") && !empty($authcfg['ldap_pam_groupdn'])) {
2320
			// do not try to reconnect
2321
			$ldapconf = "bind_policy soft\n";
2322
			// Bind/connect timelimit
2323
			$ldapconf .= "bind_timelimit {$authcfg['ldap_timeout']}\n";
2324
			$uri = ($authcfg['ldap_urltype'] == 'SSL/TLS Encrypted') ? 'ldaps' : 'ldap';
2325
			$ldapconf .= "uri {$uri}://{$authcfg['host']}/\n";
2326
			$ldapconf .= "port {$authcfg['ldap_port']}\n";
2327
			if ($authcfg['ldap_urltype'] == 'STARTTLS Encrypted')  {
2328
				$ldapconf .= "ssl start_tls\n";
2329
			} elseif ($authcfg['ldap_urltype'] == 'SSL/TLS Encrypted')  {
2330
				$ldapconf .= "ssl on\n";
2331
			}
2332
			if ($authcfg['ldap_urltype'] != 'Standard TCP') {
2333
				if ($authcfg['ldap_caref'] == 'global') {
2334
					$ldapconf .= "tls_cacertfile /etc/ssl/cert.pem\n";
2335
				} else {
2336
					$ca = array();
2337
					$ldappamcafile = "/var/etc/pam_ldap_ca.crt";
2338
					$ca['caref'] = $authcfg['ldap_caref'];
2339
					$cacrt = ca_chain($ca);
2340
					@file_put_contents($ldappamcafile, $cacrt); 
2341
					$ldapconf .= "tls_cacertfile {$ldappamcafile}\n";
2342
				}
2343
				$ldapconf .= "tls_checkpeer yes\n";
2344
			}
2345
			$ldapconf .= "ldap_version {$authcfg['ldap_protver']}\n";
2346
			$ldapconf .= "timelimit {$authcfg['ldap_timeout']}\n";
2347
			$ldapconf .= "base {$authcfg['ldap_basedn']}\n";
2348
			$scope = ($authcfg['ldap_scope' == 'one']) ? 'one' : 'sub';
2349
			$ldapconf .= "scope {$scope}\n";
2350
			$ldapconf .= "binddn {$authcfg['ldap_binddn']}\n";
2351
			$ldapconf .= "bindpw {$authcfg['ldap_bindpw']}\n";
2352
			$ldapconf .= "pam_login_attribute {$authcfg['ldap_attr_user']}\n";
2353
			$ldapconf .= "pam_member_attribute {$authcfg['ldap_attr_member']}\n";
2354
			//$ldapconf .= "pam_filter objectclass={$authcfg['ldap_attr_user']}\n";
2355
			$ldapconf .= "pam_groupdn {$authcfg['ldap_pam_groupdn']}\n";
2356
			//$ldapconf .= "pam_password ad\n";
2357

    
2358
			$pam_sshd =<<<EOD
2359
# auth
2360
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2361
auth		required	pam_unix.so		no_warn try_first_pass
2362

    
2363
# account
2364
account		required	pam_nologin.so
2365
account		required	pam_login_access.so
2366
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2367

    
2368
# session
2369
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2370
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2371
session		required	pam_permit.so
2372

    
2373
# password
2374
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2375
password	required	pam_unix.so		no_warn try_first_pass
2376

    
2377
EOD;
2378

    
2379
			$pam_system =<<<EOD
2380
# auth
2381
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2382
auth		required	pam_unix.so		no_warn try_first_pass
2383

    
2384
# account
2385
account		required	pam_login_access.so
2386
account         sufficient      pam_radius.so
2387
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2388

    
2389
# session
2390
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2391
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2392
session		required	pam_lastlog.so		no_fail
2393

    
2394
# password
2395
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2396
password	required	pam_unix.so		no_warn try_first_pass
2397

    
2398
EOD;
2399

    
2400
			$nsswitch =<<<EOD
2401
group: files ldap
2402
hosts: files dns
2403
netgroup: files
2404
networks: files
2405
passwd: files ldap
2406
shells: files
2407
services: files
2408
protocols: files
2409
rpc: files
2410

    
2411
EOD;
2412

    
2413
			@file_put_contents("/var/etc/pam_ldap.conf", $ldapconf);
2414
			@chmod("/var/etc/pam_ldap.conf", 0600);
2415
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2416
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2417
		}
2418
	}
2419

    
2420
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2421
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2422
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2423
}
2424
?>
(2-2/61)