Project

General

Profile

Download (70.9 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-2021 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.");
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['bcrypt-hash']) {
435
		if (password_verify($passwd, $user['bcrypt-hash'])) {
436
			return true;
437
		}
438
	}
439

    
440
	//for backwards compatibility
441
	if ($user['password']) {
442
		if (crypt($passwd, $user['password']) == $user['password']) {
443
			return true;
444
		}
445
	}
446

    
447
	if ($user['md5-hash']) {
448
		if (md5($passwd) == $user['md5-hash']) {
449
			return true;
450
		}
451
	}
452

    
453
	return false;
454
}
455

    
456
function local_sync_accounts($u2add, $u2del, $g2add, $g2del) {
457
	global $config, $debug;
458

    
459
	if (empty($u2add) && empty($u2del) && empty($g2add) && empty($g2del)) {
460
		/* Nothing to be done here */
461
		return;
462
	}
463

    
464
	foreach($u2del as $user) {
465
		if ($user['uid'] > 65000) {
466
			continue;
467
		} else if ($user['uid'] < 2000 && !in_array($user, $u2add)) {
468
			continue;
469
		}
470

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

    
485
		$system_user = $config['system']['user'];
486
		for ($i = 0; $i < count($system_user); $i++) {
487
			if ($system_user[$i]['name'] == $user['name']) {
488
				log_error("Removing user: {$user['name']}");
489
				unset($config['system']['user'][$i]);
490
				break;
491
			}
492
		}
493
	}
494

    
495
	foreach($g2del as $group) {
496
		if ($group['gid'] < 1999 || $group['gid'] > 65000) {
497
			continue;
498
		}
499

    
500
		$cmd = "/usr/sbin/pw groupdel -g " .
501
		    escapeshellarg($group['name']);
502
		if ($debug) {
503
			log_error(sprintf(gettext("Running: %s"), $cmd));
504
		}
505
		mwexec($cmd);
506

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

    
517
	foreach ($u2add as $user) {
518
		log_error("Adding user: {$user['name']}");
519
		$config['system']['user'][] = $user;
520
	}
521

    
522
	foreach ($g2add as $group) {
523
		log_error("Adding group: {$group['name']}");
524
		$config['system']['group'][] = $group;
525
	}
526

    
527
	/* Sort it alphabetically */
528
	usort($config['system']['user'], function($a, $b) {
529
		return strcmp($a['name'], $b['name']);
530
	});
531
	usort($config['system']['group'], function($a, $b) {
532
		return strcmp($a['name'], $b['name']);
533
	});
534

    
535
	write_config("Sync'd users and groups via XMLRPC");
536

    
537
	/* make sure the all group exists */
538
	$allgrp = getGroupEntryByGID(1998);
539
	local_group_set($allgrp, true);
540

    
541
	foreach ($u2add as $user) {
542
		local_user_set($user);
543
	}
544

    
545
	foreach ($g2add as $group) {
546
		local_group_set($group);
547
	}
548
}
549

    
550
function local_reset_accounts() {
551
	global $debug, $config;
552

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

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

    
607
	/* make sure the all group exists */
608
	$allgrp = getGroupEntryByGID(1998);
609
	local_group_set($allgrp, true);
610

    
611
	/* sync all local users */
612
	if (is_array($config['system']['user'])) {
613
		foreach ($config['system']['user'] as $user) {
614
			local_user_set($user);
615
		}
616
	}
617

    
618
	/* sync all local groups */
619
	if (is_array($config['system']['group'])) {
620
		foreach ($config['system']['group'] as $group) {
621
			local_group_set($group);
622
		}
623
	}
624
}
625

    
626
function local_user_set(& $user) {
627
	global $g, $debug;
628

    
629
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
630
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
631
		return;
632
	}
633

    
634

    
635
	$home_base = "/home/";
636
	$user_uid = $user['uid'];
637
	$user_name = $user['name'];
638
	$user_home = "{$home_base}{$user_name}";
639
	$user_shell = "/etc/rc.initial";
640
	$user_group = "nobody";
641

    
642
	// Ensure $home_base exists and is writable
643
	if (!is_dir($home_base)) {
644
		mkdir($home_base, 0755);
645
	}
646

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

    
665
	/* Lock out disabled or expired users, unless it's root/admin. */
666
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
667
		$user_shell = "/sbin/nologin";
668
		$lock_account = true;
669
	}
670

    
671
	/* root user special handling */
672
	if ($user_uid == 0) {
673
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
674
		if ($debug) {
675
			log_error(sprintf(gettext("Running: %s"), $cmd));
676
		}
677
		$fd = popen($cmd, "w");
678
		if (empty($user['bcrypt-hash'])) {
679
			fwrite($fd, $user['password']);
680
		} else {
681
			fwrite($fd, $user['bcrypt-hash']);
682
		}
683
		pclose($fd);
684
		$user_group = "wheel";
685
		$user_home = "/root";
686
		$user_shell = "/etc/rc.initial";
687
	}
688

    
689
	/* read from pw db */
690
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
691
	$pwread = fgets($fd);
692
	pclose($fd);
693
	$userattrs = explode(":", trim($pwread));
694

    
695
	$skel_dir = '/etc/skel';
696

    
697
	/* determine add or mod */
698
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
699
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
700
	} else {
701
		$user_op = "usermod";
702
	}
703

    
704
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
705
	/* add or mod pw db */
706
	$cmd = "/usr/sbin/pw {$user_op} -q " .
707
			" -u " . escapeshellarg($user_uid) .
708
			" -n " . escapeshellarg($user_name) .
709
			" -g " . escapeshellarg($user_group) .
710
			" -s " . escapeshellarg($user_shell) .
711
			" -d " . escapeshellarg($user_home) .
712
			" -c " . escapeshellarg($comment) .
713
			" -H 0 2>&1";
714

    
715
	if ($debug) {
716
		log_error(sprintf(gettext("Running: %s"), $cmd));
717
	}
718
	$fd = popen($cmd, "w");
719
	if (empty($user['bcrypt-hash'])) {
720
		fwrite($fd, $user['password']);
721
	} else {
722
		fwrite($fd, $user['bcrypt-hash']);
723
	}
724
	pclose($fd);
725

    
726
	/* create user directory if required */
727
	if (!is_dir($user_home)) {
728
		mkdir($user_home, 0700);
729
	}
730
	@chown($user_home, $user_name);
731
	@chgrp($user_home, $user_group);
732

    
733
	/* Make sure all users have last version of config files */
734
	foreach (glob("{$skel_dir}/dot.*") as $dot_file) {
735
		$target = $user_home . '/' . substr(basename($dot_file), 3);
736
		@copy($dot_file, $target);
737
		@chown($target, $user_name);
738
		@chgrp($target, $user_group);
739
	}
740

    
741
	/* write out ssh authorized key file */
742
	if ($user['authorizedkeys']) {
743
		if (!is_dir("{$user_home}/.ssh")) {
744
			@mkdir("{$user_home}/.ssh", 0700);
745
			@chown("{$user_home}/.ssh", $user_name);
746
		}
747
		$keys = base64_decode($user['authorizedkeys']);
748
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
749
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
750
	} else {
751
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
752
	}
753

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

    
757
}
758

    
759
function local_user_del($user) {
760
	global $debug;
761

    
762
	/* remove all memberships */
763
	local_user_set_groups($user);
764

    
765
	/* Don't remove /root */
766
	if ($user['uid'] != 0) {
767
		$rmhome = "-r";
768
	}
769

    
770
	/* read from pw db */
771
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
772
	$pwread = fgets($fd);
773
	pclose($fd);
774
	$userattrs = explode(":", trim($pwread));
775

    
776
	if ($userattrs[0] != $user['name']) {
777
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
778
		return;
779
	}
780

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

    
784
	if ($debug) {
785
		log_error(sprintf(gettext("Running: %s"), $cmd));
786
	}
787
	mwexec($cmd);
788

    
789
	/* Delete user from groups needs a call to write_config() */
790
	local_group_del_user($user);
791
}
792

    
793
function local_user_set_password(&$user, $password) {
794
	global $config;
795

    
796
	unset($user['password']);
797
	unset($user['md5-hash']);
798
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
799
	if (($user['name'] == $config['hasync']['username']) &&
800
	    ($config['hasync']['adminsync'] == 'on')) {
801
		$config['hasync']['new_password'] = $password;
802
	}
803
}
804

    
805
function local_user_get_groups($user, $all = false) {
806
	global $debug, $config;
807

    
808
	$groups = array();
809
	if (!is_array($config['system']['group'])) {
810
		return $groups;
811
	}
812

    
813
	foreach ($config['system']['group'] as $group) {
814
		if ($all || (!$all && ($group['name'] != "all"))) {
815
			if (is_array($group['member'])) {
816
				if (in_array($user['uid'], $group['member'])) {
817
					$groups[] = $group['name'];
818
				}
819
			}
820
		}
821
	}
822

    
823
	if ($all) {
824
		$groups[] = "all";
825
	}
826

    
827
	sort($groups);
828

    
829
	return $groups;
830

    
831
}
832

    
833
function local_user_set_groups($user, $new_groups = NULL) {
834
	global $debug, $config, $groupindex, $userindex;
835

    
836
	if (!is_array($config['system']['group'])) {
837
		return;
838
	}
839

    
840
	$cur_groups = local_user_get_groups($user, true);
841
	$mod_groups = array();
842

    
843
	if (!is_array($new_groups)) {
844
		$new_groups = array();
845
	}
846

    
847
	if (!is_array($cur_groups)) {
848
		$cur_groups = array();
849
	}
850

    
851
	/* determine which memberships to add */
852
	foreach ($new_groups as $groupname) {
853
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
854
			continue;
855
		}
856
		$group = &$config['system']['group'][$groupindex[$groupname]];
857
		$group['member'][] = $user['uid'];
858
		$mod_groups[] = $group;
859

    
860
		/*
861
		 * If it's a new user, make sure it is added before try to
862
		 * add it as a member of a group
863
		 */
864
		if (!isset($userindex[$user['uid']])) {
865
			local_user_set($user);
866
		}
867
	}
868
	unset($group);
869

    
870
	/* determine which memberships to remove */
871
	foreach ($cur_groups as $groupname) {
872
		if (in_array($groupname, $new_groups)) {
873
			continue;
874
		}
875
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
876
			continue;
877
		}
878
		$group = &$config['system']['group'][$groupindex[$groupname]];
879
		if (is_array($group['member'])) {
880
			$index = array_search($user['uid'], $group['member']);
881
			array_splice($group['member'], $index, 1);
882
			$mod_groups[] = $group;
883
		}
884
	}
885
	unset($group);
886

    
887
	/* sync all modified groups */
888
	foreach ($mod_groups as $group) {
889
		local_group_set($group);
890
	}
891
}
892

    
893
function local_group_del_user($user) {
894
	global $config;
895

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

    
900
	foreach ($config['system']['group'] as $group) {
901
		if (is_array($group['member'])) {
902
			foreach ($group['member'] as $idx => $uid) {
903
				if ($user['uid'] == $uid) {
904
					unset($config['system']['group']['member'][$idx]);
905
				}
906
			}
907
		}
908
	}
909
}
910

    
911
function local_group_set($group, $reset = false) {
912
	global $debug;
913

    
914
	$group_name = $group['name'];
915
	$group_gid = $group['gid'];
916
	$group_members = '';
917

    
918
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
919
		$group_members = implode(",", $group['member']);
920
	}
921

    
922
	if (empty($group_name)) {
923
		return;
924
	}
925

    
926
	// If the group is now remote, make sure there is no local group with the same name
927
	if ($group['scope'] == "remote") {
928
		local_group_del($group);
929
		return;
930
	}
931

    
932
	/* determine add or mod */
933
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
934
		$group_op = "groupmod -l";
935
	} else {
936
		$group_op = "groupadd -n";
937
	}
938

    
939
	/* add or mod group db */
940
	$cmd = "/usr/sbin/pw {$group_op} " .
941
		escapeshellarg($group_name) .
942
		" -g " . escapeshellarg($group_gid) .
943
		" -M " . escapeshellarg($group_members) . " 2>&1";
944

    
945
	if ($debug) {
946
		log_error(sprintf(gettext("Running: %s"), $cmd));
947
	}
948

    
949
	mwexec($cmd);
950
}
951

    
952
function local_group_del($group) {
953
	global $debug;
954

    
955
	/* delete from group db */
956
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
957

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

    
964
function ldap_test_connection($authcfg) {
965
	if ($authcfg) {
966
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
967
			$ldapproto = "ldaps";
968
		} else {
969
			$ldapproto = "ldap";
970
		}
971
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
972
		$ldapport = $authcfg['ldap_port'];
973
		if (!empty($ldapport)) {
974
			$ldapserver .= ":{$ldapport}";
975
		}
976
	} else {
977
		return false;
978
	}
979

    
980
	/* first check if there is even an LDAP server populated */
981
	if (!$ldapserver) {
982
		return false;
983
	}
984

    
985
	/* connect and see if server is up */
986
	$error = false;
987
	if (!($ldap = ldap_connect($ldapserver))) {
988
		$error = true;
989
	}
990

    
991
	if ($error == true) {
992
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
993
		return false;
994
	}
995

    
996
	/* Setup CA environment if needed. */
997
	ldap_setup_caenv($ldap, $authcfg);
998

    
999
	return true;
1000
}
1001

    
1002
function ldap_setup_caenv($ldap, $authcfg) {
1003
	global $g;
1004
	require_once("certs.inc");
1005

    
1006
	unset($caref);
1007
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
1008
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
1009
		return;
1010
	} elseif ($authcfg['ldap_caref'] == "global") {
1011
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, "/etc/ssl/");
1012
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, "/etc/ssl/cert.pem");
1013
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1014
	} else {
1015
		$caref = lookup_ca($authcfg['ldap_caref']);
1016
		$cert_details = openssl_x509_parse(base64_decode($caref['crt']));
1017
		$param = array('caref' => $authcfg['ldap_caref']);
1018
		$cachain = ca_chain($param);
1019
		if (!$caref) {
1020
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
1021
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
1022
			ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1023
			return;
1024
		}
1025

    
1026
		$cert_path = "{$g['varrun_path']}/certs";
1027
		$cert_filename = "{$cert_path}/{$cert_details['hash']}.0";
1028
		safe_mkdir($cert_path);
1029
		unlink_if_exists($cert_filename);
1030
		file_put_contents($cert_filename, $cachain);
1031
		@chmod($cert_filename, 0600);
1032

    
1033
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1034
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, $cert_path);
1035
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, $cert_filename);
1036
	}
1037
}
1038

    
1039
function ldap_test_bind($authcfg) {
1040
	global $debug, $config, $g;
1041

    
1042
	if ($authcfg) {
1043
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1044
			$ldapproto = "ldaps";
1045
		} else {
1046
			$ldapproto = "ldap";
1047
		}
1048
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1049
		$ldapport = $authcfg['ldap_port'];
1050
		if (!empty($ldapport)) {
1051
			$ldapserver .= ":{$ldapport}";
1052
		}
1053
		$ldapbasedn = $authcfg['ldap_basedn'];
1054
		$ldapbindun = $authcfg['ldap_binddn'];
1055
		$ldapbindpw = $authcfg['ldap_bindpw'];
1056
		$ldapver = $authcfg['ldap_protver'];
1057
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1058
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1059
			$ldapanon = true;
1060
		} else {
1061
			$ldapanon = false;
1062
		}
1063
	} else {
1064
		return false;
1065
	}
1066

    
1067
	/* first check if there is even an LDAP server populated */
1068
	if (!$ldapserver) {
1069
		return false;
1070
	}
1071

    
1072
	/* connect and see if server is up */
1073
	$error = false;
1074
	if (!($ldap = ldap_connect($ldapserver))) {
1075
		$error = true;
1076
	}
1077

    
1078
	if ($error == true) {
1079
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1080
		return false;
1081
	}
1082

    
1083
	/* Setup CA environment if needed. */
1084
	ldap_setup_caenv($ldap, $authcfg);
1085

    
1086
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1087
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1088
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1089
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1090
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1091

    
1092
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1093
		if (!(@ldap_start_tls($ldap))) {
1094
			log_error(sprintf(gettext("ERROR! ldap_test_bind() could not STARTTLS to server %s."), $ldapname));
1095
			@ldap_close($ldap);
1096
			return false;
1097
		}
1098
	}
1099

    
1100
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1101
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1102
	if ($ldapanon == true) {
1103
		if (!($res = @ldap_bind($ldap))) {
1104
			@ldap_close($ldap);
1105
			return false;
1106
		}
1107
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1108
		@ldap_close($ldap);
1109
		return false;
1110
	}
1111

    
1112
	@ldap_unbind($ldap);
1113

    
1114
	return true;
1115
}
1116

    
1117
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1118
	global $debug, $config, $g;
1119

    
1120
	if (!function_exists("ldap_connect")) {
1121
		return;
1122
	}
1123

    
1124
	$ous = array();
1125

    
1126
	if ($authcfg) {
1127
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1128
			$ldapproto = "ldaps";
1129
		} else {
1130
			$ldapproto = "ldap";
1131
		}
1132
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1133
		$ldapport = $authcfg['ldap_port'];
1134
		if (!empty($ldapport)) {
1135
			$ldapserver .= ":{$ldapport}";
1136
		}
1137
		$ldapbasedn = $authcfg['ldap_basedn'];
1138
		$ldapbindun = $authcfg['ldap_binddn'];
1139
		$ldapbindpw = $authcfg['ldap_bindpw'];
1140
		$ldapver = $authcfg['ldap_protver'];
1141
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1142
			$ldapanon = true;
1143
		} else {
1144
			$ldapanon = false;
1145
		}
1146
		$ldapname = $authcfg['name'];
1147
		$ldapfallback = false;
1148
		$ldapscope = $authcfg['ldap_scope'];
1149
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1150
	} else {
1151
		return false;
1152
	}
1153

    
1154
	/* first check if there is even an LDAP server populated */
1155
	if (!$ldapserver) {
1156
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
1157
		return $ous;
1158
	}
1159

    
1160
	/* connect and see if server is up */
1161
	$error = false;
1162
	if (!($ldap = ldap_connect($ldapserver))) {
1163
		$error = true;
1164
	}
1165

    
1166
	if ($error == true) {
1167
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1168
		return $ous;
1169
	}
1170

    
1171
	/* Setup CA environment if needed. */
1172
	ldap_setup_caenv($ldap, $authcfg);
1173

    
1174
	$ldapfilter = "(|(ou=*)(cn=Users))";
1175

    
1176
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1177
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1178
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1179
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1180
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1181

    
1182
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1183
		if (!(@ldap_start_tls($ldap))) {
1184
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not STARTTLS to server %s."), $ldapname));
1185
			@ldap_close($ldap);
1186
			return false;
1187
		}
1188
	}
1189

    
1190
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1191
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1192
	if ($ldapanon == true) {
1193
		if (!($res = @ldap_bind($ldap))) {
1194
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1195
			@ldap_close($ldap);
1196
			return $ous;
1197
		}
1198
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1199
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1200
		@ldap_close($ldap);
1201
		return $ous;
1202
	}
1203

    
1204
	if ($ldapscope == "one") {
1205
		$ldapfunc = "ldap_list";
1206
	} else {
1207
		$ldapfunc = "ldap_search";
1208
	}
1209

    
1210
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1211
	$info = @ldap_get_entries($ldap, $search);
1212

    
1213
	if (is_array($info)) {
1214
		foreach ($info as $inf) {
1215
			if (!$show_complete_ou) {
1216
				$inf_split = explode(",", $inf['dn']);
1217
				$ou = $inf_split[0];
1218
				$ou = str_replace("OU=", "", $ou);
1219
				$ou = str_replace("CN=", "", $ou);
1220
			} else {
1221
				if ($inf['dn']) {
1222
					$ou = $inf['dn'];
1223
				}
1224
			}
1225
			if ($ou) {
1226
				$ous[] = $ou;
1227
			}
1228
		}
1229
	}
1230

    
1231
	@ldap_unbind($ldap);
1232

    
1233
	return $ous;
1234
}
1235

    
1236
function ldap_get_groups($username, $authcfg) {
1237
	global $debug, $config;
1238

    
1239
	if (!function_exists("ldap_connect")) {
1240
		return;
1241
	}
1242

    
1243
	if (!$username) {
1244
		return false;
1245
	}
1246

    
1247
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1248
		$username_split = explode("@", $username);
1249
		$username = $username_split[0];
1250
	}
1251

    
1252
	if (stristr($username, "\\")) {
1253
		$username_split = explode("\\", $username);
1254
		$username = $username_split[0];
1255
	}
1256

    
1257
	//log_error("Getting LDAP groups for {$username}.");
1258
	if ($authcfg) {
1259
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1260
			$ldapproto = "ldaps";
1261
		} else {
1262
			$ldapproto = "ldap";
1263
		}
1264
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1265
		$ldapport = $authcfg['ldap_port'];
1266
		if (!empty($ldapport)) {
1267
			$ldapserver .= ":{$ldapport}";
1268
		}
1269
		$ldapbasedn = $authcfg['ldap_basedn'];
1270
		$ldapbindun = $authcfg['ldap_binddn'];
1271
		$ldapbindpw = $authcfg['ldap_bindpw'];
1272
		$ldapauthcont = $authcfg['ldap_authcn'];
1273
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1274
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1275
		$ldaptype = "";
1276
		$ldapver = $authcfg['ldap_protver'];
1277
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1278
			$ldapanon = true;
1279
		} else {
1280
			$ldapanon = false;
1281
		}
1282
		$ldapname = $authcfg['name'];
1283
		$ldapfallback = false;
1284
		$ldapscope = $authcfg['ldap_scope'];
1285
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1286
	} else {
1287
		return false;
1288
	}
1289

    
1290
	if (isset($authcfg['ldap_rfc2307'])) {
1291
		$ldapdn = $ldapbasedn;
1292
	} else {
1293
		$ldapdn = $_SESSION['ldapdn'];
1294
	}
1295

    
1296
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1297
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1298
	$memberof = array();
1299

    
1300
	/* connect and see if server is up */
1301
	$error = false;
1302
	if (!($ldap = ldap_connect($ldapserver))) {
1303
		$error = true;
1304
	}
1305

    
1306
	if ($error == true) {
1307
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1308
		return $memberof;
1309
	}
1310

    
1311
	/* Setup CA environment if needed. */
1312
	ldap_setup_caenv($ldap, $authcfg);
1313

    
1314
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1315
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1316
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1317
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1318
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1319

    
1320
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1321
		if (!(@ldap_start_tls($ldap))) {
1322
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not STARTTLS to server %s."), $ldapname));
1323
			@ldap_close($ldap);
1324
			return false;
1325
		}
1326
	}
1327

    
1328
	/* bind as user that has rights to read group attributes */
1329
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1330
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1331
	if ($ldapanon == true) {
1332
		if (!($res = @ldap_bind($ldap))) {
1333
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1334
			@ldap_close($ldap);
1335
			return false;
1336
		}
1337
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1338
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1339
		@ldap_close($ldap);
1340
		return $memberof;
1341
	}
1342

    
1343
	/* get groups from DN found */
1344
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1345
	/* since we know the DN is in $_SESSION['ldapdn'] */
1346
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1347
	if ($ldapscope == "one") {
1348
		$ldapfunc = "ldap_list";
1349
	} else {
1350
		$ldapfunc = "ldap_search";
1351
	}
1352

    
1353
	if (isset($authcfg['ldap_rfc2307'])) {
1354
		if (isset($authcfg['ldap_rfc2307_userdn'])) {
1355
			$ldac_splits = explode(";", $ldapauthcont);
1356
			foreach ($ldac_splits as $i => $ldac_split) {
1357
				$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1358
				$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1359
				$ldapfilter = "({$ldapnameattribute}={$username})";
1360
				if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1361
					$ldapdn = $ldac_split;
1362
				} else {
1363
					$ldapdn = $ldapsearchbasedn;
1364
				}
1365
				$usersearch = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1366
				$userinfo = @ldap_get_entries($ldap, $usersearch);
1367
			}
1368
			$username = $userinfo[0]['dn'];
1369
		}
1370
		$ldapfilter = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1371
	} else {
1372
		$ldapfilter = "({$ldapnameattribute}={$username})";
1373
	}
1374

    
1375
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1376
	$info = @ldap_get_entries($ldap, $search);
1377

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

    
1380
	if (is_array($gresults)) {
1381
		/* Iterate through the groups and throw them into an array */
1382
		foreach ($gresults as $grp) {
1383
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1384
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1385
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1386
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1387
			}
1388
		}
1389
	}
1390

    
1391
	/* Time to close LDAP connection */
1392
	@ldap_unbind($ldap);
1393

    
1394
	$groups = print_r($memberof, true);
1395

    
1396
	//log_error("Returning groups ".$groups." for user $username");
1397

    
1398
	return $memberof;
1399
}
1400

    
1401
function ldap_format_host($host) {
1402
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1403
}
1404

    
1405
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1406
	global $debug, $config;
1407

    
1408
	if (!$username) {
1409
		$attributes['error_message'] = gettext("Invalid Login.");
1410
		return false;
1411
	}
1412

    
1413
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1414
		$attributes['error_message'] = gettext("Invalid credentials.");
1415
		return false;
1416
	}
1417

    
1418
	if (!function_exists("ldap_connect")) {
1419
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1420
		$attributes['error_message'] = gettext("Internal error during authentication.");
1421
		return null;
1422
	}
1423

    
1424
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1425
		$username_split = explode("@", $username);
1426
		$username = $username_split[0];
1427
	}
1428
	if (stristr($username, "\\")) {
1429
		$username_split = explode("\\", $username);
1430
		$username = $username_split[0];
1431
	}
1432

    
1433
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1434

    
1435
	if ($authcfg) {
1436
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1437
			$ldapproto = "ldaps";
1438
		} else {
1439
			$ldapproto = "ldap";
1440
		}
1441
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1442
		$ldapport = $authcfg['ldap_port'];
1443
		if (!empty($ldapport)) {
1444
			$ldapserver .= ":{$ldapport}";
1445
		}
1446
		$ldapbasedn = $authcfg['ldap_basedn'];
1447
		$ldapbindun = $authcfg['ldap_binddn'];
1448
		$ldapbindpw = $authcfg['ldap_bindpw'];
1449
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1450
			$ldapanon = true;
1451
		} else {
1452
			$ldapanon = false;
1453
		}
1454
		$ldapauthcont = $authcfg['ldap_authcn'];
1455
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1456
		$ldapgroupattribute = $authcfg['ldap_attr_member'];
1457
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1458
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1459
		$ldapfilter = "";
1460
		if (!$ldapextendedqueryenabled) {
1461
			$ldapfilter = "({$ldapnameattribute}={$username})";
1462
		} else {
1463
			if (isset($authcfg['ldap_rfc2307'])) {
1464
				$ldapfilter = "({$ldapnameattribute}={$username})";
1465
				$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1466
			} else {
1467
				$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1468
			}
1469
		}
1470
		$ldaptype = "";
1471
		$ldapver = $authcfg['ldap_protver'];
1472
		$ldapname = $authcfg['name'];
1473
		$ldapscope = $authcfg['ldap_scope'];
1474
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1475
	} else {
1476
		return null;
1477
	}
1478

    
1479
	/* first check if there is even an LDAP server populated */
1480
	if (!$ldapserver) {
1481
		log_error(gettext("ERROR! could not find details of the LDAP server used for authentication."));
1482
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1483
		return null;
1484
	}
1485

    
1486
	/* Make sure we can connect to LDAP */
1487
	$error = false;
1488
	if (!($ldap = ldap_connect($ldapserver))) {
1489
		$error = true;
1490
	}
1491

    
1492
	/* Setup CA environment if needed. */
1493
	ldap_setup_caenv($ldap, $authcfg);
1494

    
1495
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1496
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1497
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1498
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1499
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1500

    
1501
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1502
		if (!(@ldap_start_tls($ldap))) {
1503
			log_error(sprintf(gettext("ERROR! could not connect to LDAP server %s using STARTTLS."), $ldapname));
1504
			$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1505
			@ldap_close($ldap);
1506
			return null;
1507
		}
1508
	}
1509

    
1510
	if ($error == true) {
1511
		$errormsg = sprintf(gettext("ERROR! Could not connect to server %s."), $ldapname);
1512
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1513
		return null;
1514
	}
1515

    
1516
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1517
	$error = false;
1518
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1519
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1520
	if ($ldapanon == true) {
1521
		if (!($res = @ldap_bind($ldap))) {
1522
			$error = true;
1523
		}
1524
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1525
		$error = true;
1526
	}
1527

    
1528
	if ($error == true) {
1529
		@ldap_close($ldap);
1530
		log_error(sprintf(gettext("ERROR! Could not bind to LDAP server %s. Please check the bind credentials."), $ldapname));
1531
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1532
		return null;
1533
	}
1534

    
1535
	/* Get LDAP Authcontainers and split em up. */
1536
	$ldac_splits = explode(";", $ldapauthcont);
1537

    
1538
	/* setup the usercount so we think we haven't found anyone yet */
1539
	$usercount = 0;
1540

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

    
1585
		if (isset($ldapgroupfilter) && !$groupsearch) {
1586
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1587
			continue;
1588
		}
1589
		if (isset($groupsearch)) {
1590
			$validgroup = ldap_count_entries($ldap, $groupsearch);
1591
			if ($debug) {
1592
				log_auth(sprintf(gettext("LDAP group search: %s results."), $validgroup));
1593
			}
1594
		}
1595
		$info = ldap_get_entries($ldap, $search);
1596
		$matches = $info['count'];
1597
		if ($matches == 1) {
1598
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1599
			$_SESSION['ldapou'] = $ldac_split[$i];
1600
			$_SESSION['ldapon'] = "true";
1601
			$usercount = 1;
1602
			break;
1603
		}
1604
	}
1605

    
1606
	if ($usercount != 1) {
1607
		@ldap_unbind($ldap);
1608
		if ($debug) {
1609
			if ($usercount === 0) {
1610
				log_error(sprintf(gettext("ERROR! LDAP search failed, no user matching %s was found."), $username));
1611
			} else {
1612
				log_error(sprintf(gettext("ERROR! LDAP search failed, multiple users matching %s were found."), $username));
1613
			}
1614
		}
1615
		$attributes['error_message'] = gettext("Invalid login specified.");
1616
		return false;
1617
	}
1618

    
1619
	/* Now lets bind as the user we found */
1620
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1621
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1622
		if ($debug) {
1623
			log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1624
		}
1625
		@ldap_unbind($ldap);
1626
		return false;
1627
	}
1628

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

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

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

    
1641
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1642
		return false;
1643
	}
1644

    
1645
	return true;
1646
}
1647

    
1648
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1649
	global $debug, $config;
1650
	$ret = false;
1651

    
1652
	require_once("Auth/RADIUS.php");
1653
	require_once("Crypt/CHAP.php");
1654

    
1655
	if ($authcfg) {
1656
		$radiusservers = array();
1657
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1658
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1659
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1660
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1661
		if(isset($authcfg['radius_protocol'])) {
1662
			$radius_protocol = $authcfg['radius_protocol'];
1663
		} else {
1664
			$radius_protocol = 'PAP';
1665
		}
1666
	} else {
1667
		log_error(gettext("ERROR! could not find details of the RADIUS server used for authentication."));
1668
		$attributes['error_message'] =  gettext("Internal error during authentication.");
1669
		return null;
1670
	}
1671

    
1672
	// Create our instance
1673
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1674
	$rauth = new $classname($username, $password);
1675

    
1676
	/* Add new servers to our instance */
1677
	foreach ($radiusservers as $radsrv) {
1678
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1679
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1680
	}
1681

    
1682
	// Construct data package
1683
	$rauth->username = $username;
1684
	switch ($radius_protocol) {
1685
		case 'CHAP_MD5':
1686
		case 'MSCHAPv1':
1687
			$classname = $radius_protocol == 'MSCHAPv1' ? 'Crypt_CHAP_MSv1' : 'Crypt_CHAP_MD5';
1688
			$crpt = new $classname;
1689
			$crpt->username = $username;
1690
			$crpt->password = $password;
1691
			$rauth->challenge = $crpt->challenge;
1692
			$rauth->chapid = $crpt->chapid;
1693
			$rauth->response = $crpt->challengeResponse();
1694
			$rauth->flags = 1;
1695
			break;
1696

    
1697
		case 'MSCHAPv2':
1698
			$crpt = new Crypt_CHAP_MSv2;
1699
			$crpt->username = $username;
1700
			$crpt->password = $password;
1701
			$rauth->challenge = $crpt->authChallenge;
1702
			$rauth->peerChallenge = $crpt->peerChallenge;
1703
			$rauth->chapid = $crpt->chapid;
1704
			$rauth->response = $crpt->challengeResponse();
1705
			break;
1706

    
1707
		default:
1708
			$rauth->password = $password;
1709
			break;
1710
	}
1711

    
1712
	if (PEAR::isError($rauth->start())) {
1713
		$ret = null;
1714
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1715
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1716
	} else {
1717
		$nasid = $attributes['nas_identifier'];
1718
		$nasip = $authcfg['radius_nasip_attribute'];
1719
		if (empty($nasid)) {
1720
			$nasid = gethostname(); //If no RADIUS NAS-Identifier is given : we use pfsense's hostname as NAS-Identifier
1721
		}
1722
		if (!is_ipaddr($nasip)) {
1723
			$nasip = get_interface_ip($nasip);
1724

    
1725
			if (!is_ipaddr($nasip)) {
1726
				/* use first interface with IP as fallback for NAS-IP-Address
1727
				 * see https://redmine.pfsense.org/issues/11109 */
1728
				foreach (get_configured_interface_list() as $if) {
1729
					$nasip = get_interface_ip($if);
1730
					if (is_ipaddr($nasip)) {
1731
						break;
1732
					}
1733
				}
1734
			}
1735
		}
1736
		$nasmac = get_interface_mac(find_ip_interface($nasip));
1737

    
1738
		$rauth->putAttribute(RADIUS_NAS_IP_ADDRESS, $nasip, "addr");
1739
		$rauth->putAttribute(RADIUS_NAS_IDENTIFIER, $nasid);
1740

    
1741
		if(!empty($attributes['calling_station_id'])) {
1742
			$rauth->putAttribute(RADIUS_CALLING_STATION_ID, $attributes['calling_station_id']);
1743
		}
1744
		// Carefully check that interface has a MAC address
1745
		if(!empty($nasmac)) {
1746
			$nasmac = mac_format($nasmac);
1747
			$rauth->putAttribute(RADIUS_CALLED_STATION_ID, $nasmac.':'.gethostname());
1748
		}
1749
		if(!empty($attributes['nas_port_type'])) {
1750
			$rauth->putAttribute(RADIUS_NAS_PORT_TYPE, $attributes['nas_port_type']);
1751
		}
1752
		if(!empty($attributes['nas_port'])) {
1753
			$rauth->putAttribute(RADIUS_NAS_PORT, intval($attributes['nas_port']), 'integer');
1754
		}
1755
		if(!empty($attributes['framed_ip']) && is_ipaddr($attributes['framed_ip'])) {
1756
			$rauth->putAttribute(RADIUS_FRAMED_IP_ADDRESS, $attributes['framed_ip'], "addr");
1757
		}
1758
	}
1759

    
1760
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1761

    
1762
	/* Send request */
1763
	$result = $rauth->send();
1764
	if (PEAR::isError($result)) {
1765
		log_error(sprintf(gettext("Error during RADIUS authentication : %s"), $rauth->getError()));
1766
		$attributes['error_message'] = gettext("Error : could not connect to authentication server.");
1767
		$ret = null;
1768
	} else if ($result === true) {
1769
		$ret = true;
1770
	} else {
1771
		$ret = false;
1772
	}
1773

    
1774

    
1775
	// Get attributes, even if auth failed.
1776
	if ($rauth->getAttributes()) {
1777
	$attributes = array_merge($attributes,$rauth->listAttributes());
1778

    
1779
	// We convert the session_terminate_time to unixtimestamp if its set before returning the whole array to our caller
1780
	if (!empty($attributes['session_terminate_time'])) {
1781
			$stt = &$attributes['session_terminate_time'];
1782
			$stt = strtotime(preg_replace("/\+(\d+):(\d+)$/", " +\${1}\${2}", preg_replace("/(\d+)T(\d+)/", "\${1} \${2}",$stt)));
1783
		}
1784
	}
1785

    
1786
	// close OO RADIUS_AUTHENTICATION
1787
	$rauth->close();
1788

    
1789
	return $ret;
1790
}
1791

    
1792
/*
1793
	$attributes must contain a "class" key containing the groups and local
1794
	groups must exist to match.
1795
*/
1796
function radius_get_groups($attributes) {
1797
	$groups = array();
1798
	if (!empty($attributes) && is_array($attributes) && (!empty($attributes['class']) || !empty($attributes['class_int']))) {
1799
		/* Some RADIUS servers return multiple class attributes, so check them all. */
1800
		$groups = array();
1801
		if (!empty($attributes['class']) && is_array($attributes['class'])) {
1802
			foreach ($attributes['class'] as $class) {
1803
				$groups = array_unique(array_merge($groups, explode(";", $class)));
1804
			}
1805
		}
1806

    
1807
		foreach ($groups as & $grp) {
1808
			$grp = trim($grp);
1809
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1810
				$grp = substr($grp, 3);
1811
			}
1812
		}
1813
	}
1814
	return $groups;
1815
}
1816

    
1817
function get_user_expiration_date($username) {
1818
	$user = getUserEntry($username);
1819
	if ($user['expires']) {
1820
		return $user['expires'];
1821
	}
1822
}
1823

    
1824
function is_account_expired($username) {
1825
	$expirydate = get_user_expiration_date($username);
1826
	if ($expirydate) {
1827
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1828
			return true;
1829
		}
1830
	}
1831

    
1832
	return false;
1833
}
1834

    
1835
function is_account_disabled($username) {
1836
	$user = getUserEntry($username);
1837
	if (isset($user['disabled'])) {
1838
		return true;
1839
	}
1840

    
1841
	return false;
1842
}
1843

    
1844
function get_user_settings($username) {
1845
	global $config;
1846
	$settings = array();
1847
	$settings['widgets'] = $config['widgets'];
1848
	$settings['webgui']['dashboardcolumns'] = $config['system']['webgui']['dashboardcolumns'];
1849
	$settings['webgui']['webguihostnamemenu'] = $config['system']['webgui']['webguihostnamemenu'];
1850
	$settings['webgui']['webguicss'] = $config['system']['webgui']['webguicss'];
1851
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1852
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1853
	$settings['webgui']['dashboardavailablewidgetspanel'] = isset($config['system']['webgui']['dashboardavailablewidgetspanel']);
1854
	$settings['webgui']['webguifixedmenu'] = isset($config['system']['webgui']['webguifixedmenu']);
1855
	$settings['webgui']['webguileftcolumnhyper'] = isset($config['system']['webgui']['webguileftcolumnhyper']);
1856
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1857
	$settings['webgui']['systemlogsfilterpanel'] = isset($config['system']['webgui']['systemlogsfilterpanel']);
1858
	$settings['webgui']['systemlogsmanagelogpanel'] = isset($config['system']['webgui']['systemlogsmanagelogpanel']);
1859
	$settings['webgui']['statusmonitoringsettingspanel'] = isset($config['system']['webgui']['statusmonitoringsettingspanel']);
1860
	$settings['webgui']['pagenamefirst'] = isset($config['system']['webgui']['pagenamefirst']);
1861
	$user = getUserEntry($username);
1862
	if (isset($user['customsettings'])) {
1863
		$settings['customsettings'] = true;
1864
		if (isset($user['widgets'])) {
1865
			// This includes the 'sequence', and any widgetname-config per-widget settings.
1866
			$settings['widgets'] = $user['widgets'];
1867
		}
1868
		if (isset($user['dashboardcolumns'])) {
1869
			$settings['webgui']['dashboardcolumns'] = $user['dashboardcolumns'];
1870
		}
1871
		if (isset($user['webguicss'])) {
1872
			$settings['webgui']['webguicss'] = $user['webguicss'];
1873
		}
1874
		if (isset($user['webguihostnamemenu'])) {
1875
			$settings['webgui']['webguihostnamemenu'] = $user['webguihostnamemenu'];
1876
		}
1877
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1878
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1879
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1880
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1881
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1882
		$settings['webgui']['systemlogsfilterpanel'] = isset($user['systemlogsfilterpanel']);
1883
		$settings['webgui']['systemlogsmanagelogpanel'] = isset($user['systemlogsmanagelogpanel']);
1884
		$settings['webgui']['statusmonitoringsettingspanel'] = isset($user['statusmonitoringsettingspanel']);
1885
		$settings['webgui']['pagenamefirst'] = isset($user['pagenamefirst']);
1886
	} else {
1887
		$settings['customsettings'] = false;
1888
	}
1889

    
1890
	if ($settings['webgui']['dashboardcolumns'] < 1) {
1891
		$settings['webgui']['dashboardcolumns'] = 2;
1892
	}
1893

    
1894
	return $settings;
1895
}
1896

    
1897
function save_widget_settings($username, $settings, $message = "") {
1898
	global $config, $userindex;
1899
	$user = getUserEntry($username);
1900

    
1901
	if (strlen($message) > 0) {
1902
		$msgout = $message;
1903
	} else {
1904
		$msgout = gettext("Widget configuration has been changed.");
1905
	}
1906

    
1907
	if (isset($user['customsettings'])) {
1908
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1909
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1910
	} else {
1911
		$config['widgets'] = $settings;
1912
		write_config($msgout);
1913
	}
1914
}
1915

    
1916
function auth_get_authserver($name) {
1917
	global $config;
1918

    
1919
	if (is_array($config['system']['authserver'])) {
1920
		foreach ($config['system']['authserver'] as $authcfg) {
1921
			if ($authcfg['name'] == $name) {
1922
				return $authcfg;
1923
			}
1924
		}
1925
	}
1926
	if ($name == "Local Database") {
1927
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1928
	}
1929
}
1930

    
1931
function auth_get_authserver_list() {
1932
	global $config;
1933

    
1934
	$list = array();
1935

    
1936
	if (is_array($config['system']['authserver'])) {
1937
		foreach ($config['system']['authserver'] as $authcfg) {
1938
			/* Add support for disabled entries? */
1939
			$list[$authcfg['name']] = $authcfg;
1940
		}
1941
	}
1942

    
1943
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1944
	return $list;
1945
}
1946

    
1947
function getUserGroups($username, $authcfg, &$attributes = array()) {
1948
	global $config;
1949

    
1950
	$allowed_groups = array();
1951

    
1952
	switch ($authcfg['type']) {
1953
		case 'ldap':
1954
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1955
			break;
1956
		case 'radius':
1957
			$allowed_groups = @radius_get_groups($attributes);
1958
			break;
1959
		default:
1960
			$user = getUserEntry($username);
1961
			$allowed_groups = @local_user_get_groups($user, true);
1962
			break;
1963
	}
1964

    
1965
	$member_groups = array();
1966
	if (is_array($config['system']['group'])) {
1967
		foreach ($config['system']['group'] as $group) {
1968
			if (in_array($group['name'], $allowed_groups)) {
1969
				$member_groups[] = $group['name'];
1970
			}
1971
		}
1972
	}
1973

    
1974
	return $member_groups;
1975
}
1976

    
1977
/*
1978
Possible return values :
1979
true : authentication worked
1980
false : authentication failed (invalid login/password, not enough permission, etc...)
1981
null : error during authentication process (unable to reach remote server, etc...)
1982
*/
1983
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1984

    
1985
	if (is_array($username) || is_array($password)) {
1986
		return false;
1987
	}
1988

    
1989
	if (!$authcfg) {
1990
		return local_backed($username, $password, $attributes);
1991
	}
1992

    
1993
	$authenticated = false;
1994
	switch ($authcfg['type']) {
1995
		case 'ldap':
1996
			try {
1997
				$authenticated = ldap_backed($username, $password, $authcfg, $attributes);
1998
			} catch (Exception $e) {
1999
				log_error(sprintf(gettext("LDAP authentication error: %s"), $e->getMessage()));
2000
			}
2001
			break;
2002

    
2003
			break;
2004
		case 'radius':
2005
			try {
2006
				$authenticated = radius_backed($username, $password, $authcfg, $attributes);
2007
			} catch (Exception $e) {
2008
				log_error(sprintf(gettext("RADIUS authentication error: %s"), $e->getMessage()));
2009
			}
2010
			break;
2011
		default:
2012
			/* lookup user object by name */
2013
			try {
2014
				$authenticated = local_backed($username, $password, $attributes);
2015
			} catch (Exception $e) {
2016
				log_error(sprintf(gettext("Local authentication error: %s"), $e->getMessage()));
2017
			}
2018
			break;
2019
		}
2020

    
2021
	return $authenticated;
2022
}
2023

    
2024
function session_auth() {
2025
	global $config, $_SESSION, $page;
2026

    
2027
	// Handle HTTPS httponly and secure flags
2028
	$currentCookieParams = session_get_cookie_params();
2029
	session_set_cookie_params(
2030
		$currentCookieParams["lifetime"],
2031
		$currentCookieParams["path"],
2032
		NULL,
2033
		($config['system']['webgui']['protocol'] == "https"),
2034
		true
2035
	);
2036

    
2037
	phpsession_begin();
2038

    
2039
	// Detect protocol change
2040
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2041
		phpsession_end();
2042
		return false;
2043
	}
2044

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

    
2092
	/* Show login page if they aren't logged in */
2093
	if (empty($_SESSION['Logged_In'])) {
2094
		phpsession_end(true);
2095
		return false;
2096
	}
2097

    
2098
	/* If session timeout isn't set, we don't mark sessions stale */
2099
	if (!isset($config['system']['webgui']['session_timeout'])) {
2100
		/* Default to 4 hour timeout if one is not set */
2101
		if ($_SESSION['last_access'] < (time() - 14400)) {
2102
			$_POST['logout'] = true;
2103
			$_SESSION['Logout'] = true;
2104
		} else {
2105
			$_SESSION['last_access'] = time();
2106
		}
2107
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2108
		/* only update if it wasn't ajax */
2109
		if (!isAjax()) {
2110
			$_SESSION['last_access'] = time();
2111
		}
2112
	} else {
2113
		/* Check for stale session */
2114
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2115
			$_POST['logout'] = true;
2116
			$_SESSION['Logout'] = true;
2117
		} else {
2118
			/* only update if it wasn't ajax */
2119
			if (!isAjax()) {
2120
				$_SESSION['last_access'] = time();
2121
			}
2122
		}
2123
	}
2124

    
2125
	/* user hit the logout button */
2126
	if (isset($_POST['logout'])) {
2127

    
2128
		if ($_SESSION['Logout']) {
2129
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2130
		} else {
2131
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], get_user_remote_address() . get_user_remote_authsource()));
2132
		}
2133

    
2134
		/* wipe out $_SESSION */
2135
		$_SESSION = array();
2136

    
2137
		if (isset($_COOKIE[session_name()])) {
2138
			setcookie(session_name(), '', time()-42000, '/');
2139
		}
2140

    
2141
		/* and destroy it */
2142
		phpsession_destroy();
2143

    
2144
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2145
		$scriptElms = count($scriptName);
2146
		$scriptName = $scriptName[$scriptElms-1];
2147

    
2148
		if (isAjax()) {
2149
			return false;
2150
		}
2151

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

    
2155
		return false;
2156
	}
2157

    
2158
	/*
2159
	 * this is for debugging purpose if you do not want to use Ajax
2160
	 * to submit a HTML form. It basically disables the observation
2161
	 * of the submit event and hence does not trigger Ajax.
2162
	 */
2163
	if ($_REQUEST['disable_ajax']) {
2164
		$_SESSION['NO_AJAX'] = "True";
2165
	}
2166

    
2167
	/*
2168
	 * Same to re-enable Ajax.
2169
	 */
2170
	if ($_REQUEST['enable_ajax']) {
2171
		unset($_SESSION['NO_AJAX']);
2172
	}
2173
	phpsession_end(true);
2174
	return true;
2175
}
2176

    
2177
function print_credit() {
2178
	global $g;
2179

    
2180
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_label"] . '</a>' .
2181
			gettext(' is developed and maintained by ') .
2182
			'<a target="_blank" href="https://netgate.com">Netgate. </a>' . ' &copy; ESF ' . $g["product_copyright_years"] .
2183
			'<a target="_blank" href="https://pfsense.org/license">' .
2184
			gettext(' View license.') . '</a>';
2185
}
2186
function get_user_remote_address() {
2187
	$remote_address = $_SERVER['REMOTE_ADDR'];
2188
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
2189
		$remote_address .= "[{$_SERVER['HTTP_CLIENT_IP']}]";
2190
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
2191
		$remote_address .= "[{$_SERVER['HTTP_X_FORWARDED_FOR']}]";
2192
	}
2193
	return $remote_address;
2194
}
2195
function get_user_remote_authsource() {
2196
	$authsource = "";
2197
	if (!empty($_SESSION['authsource'])) {
2198
		$authsource .= " ({$_SESSION['authsource']})";
2199
	}
2200
	return $authsource;
2201
}
2202

    
2203
function set_pam_auth() {
2204
	global $config;
2205

    
2206
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2207

    
2208
	unlink_if_exists("/etc/radius.conf");
2209
	unlink_if_exists("/var/etc/pam_ldap.conf");
2210
	unlink_if_exists("/var/etc/pam_ldap_ca.crt");
2211

    
2212
	$header = "# This file is automatically generated. Do not edit.\n\n";
2213
	$pam_sshd =<<<EOD
2214
# auth
2215
auth		required	pam_unix.so		no_warn try_first_pass
2216

    
2217
# account
2218
account		required	pam_nologin.so
2219
account		required	pam_login_access.so
2220
account		required	pam_unix.so
2221

    
2222
# session
2223
session		required	pam_permit.so
2224

    
2225
# password
2226
password	required	pam_unix.so		no_warn try_first_pass
2227

    
2228
EOD;
2229

    
2230
	$pam_system =<<<EOD
2231
# auth
2232
auth		required	pam_unix.so		no_warn try_first_pass
2233

    
2234
# account
2235
account		required	pam_login_access.so
2236
account		required	pam_unix.so
2237

    
2238
# session
2239
session		required	pam_lastlog.so		no_fail
2240

    
2241
# password
2242
password	required	pam_unix.so		no_warn try_first_pass
2243

    
2244
EOD;
2245

    
2246
	$nsswitch =<<<EOD
2247
group: files
2248
hosts: files dns
2249
netgroup: files
2250
networks: files
2251
passwd: files
2252
shells: files
2253
services: files
2254
protocols: files
2255
rpc: files
2256

    
2257
EOD;
2258

    
2259
	if (isset($config['system']['webgui']['shellauth'])) {
2260
		if (($authcfg['type'] == "radius") && isset($authcfg['radius_auth_port'])) {
2261
			$radius_conf = "auth {$authcfg['host']}:{$authcfg['radius_auth_port']} " .
2262
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2263
			if (isset($authcfg['radius_acct_port'])) {
2264
				$radius_conf .= "acct {$authcfg['host']}:{$authcfg['radius_acct_port']} " .
2265
					"{$authcfg['radius_secret']} {$authcfg['radius_timeout']}\n";
2266
			}
2267
			
2268
			$pam_sshd =<<<EOD
2269
# auth
2270
auth            sufficient      pam_radius.so
2271
auth		required	pam_unix.so		no_warn try_first_pass
2272

    
2273
# account
2274
account		required	pam_nologin.so
2275
account		required	pam_login_access.so
2276
account         sufficient      pam_radius.so
2277

    
2278
# session
2279
session		required	pam_permit.so
2280

    
2281
# password
2282
password        sufficient      pam_radius.so
2283
password	required	pam_unix.so		no_warn try_first_pass
2284

    
2285
EOD;
2286

    
2287
			$pam_system =<<<EOD
2288
# auth
2289
auth            sufficient      pam_radius.so
2290
auth		required	pam_unix.so		no_warn try_first_pass
2291

    
2292
# account
2293
account		required	pam_login_access.so
2294
account         sufficient      pam_radius.so
2295

    
2296
# session
2297
session		required	pam_lastlog.so		no_fail
2298

    
2299
# password
2300
password        sufficient      pam_radius.so
2301
password	required	pam_unix.so		no_warn try_first_pass
2302

    
2303
EOD;
2304

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

    
2345
			$pam_sshd =<<<EOD
2346
# auth
2347
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2348
auth		required	pam_unix.so		no_warn try_first_pass
2349

    
2350
# account
2351
account		required	pam_nologin.so
2352
account		required	pam_login_access.so
2353
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2354

    
2355
# session
2356
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2357
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2358
session		required	pam_permit.so
2359

    
2360
# password
2361
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2362
password	required	pam_unix.so		no_warn try_first_pass
2363

    
2364
EOD;
2365

    
2366
			$pam_system =<<<EOD
2367
# auth
2368
auth            sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2369
auth		required	pam_unix.so		no_warn try_first_pass
2370

    
2371
# account
2372
account		required	pam_login_access.so
2373
account         sufficient      pam_radius.so
2374
account         sufficient      /usr/local/lib/pam_ldap.so	ignore_authinfo_unavail ignore_unknown_user config=/var/etc/pam_ldap.conf
2375

    
2376
# session
2377
session		required	/usr/local/lib/pam_mkhomedir.so	umask=0077 skel=/etc/skel/ silent
2378
session		sufficient	/usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2379
session		required	pam_lastlog.so		no_fail
2380

    
2381
# password
2382
password        sufficient      /usr/local/lib/pam_ldap.so	config=/var/etc/pam_ldap.conf
2383
password	required	pam_unix.so		no_warn try_first_pass
2384

    
2385
EOD;
2386

    
2387
			$nsswitch =<<<EOD
2388
group: files ldap
2389
hosts: files dns
2390
netgroup: files
2391
networks: files
2392
passwd: files ldap
2393
shells: files
2394
services: files
2395
protocols: files
2396
rpc: files
2397

    
2398
EOD;
2399

    
2400
			@file_put_contents("/var/etc/pam_ldap.conf", $ldapconf);
2401
			@chmod("/var/etc/pam_ldap.conf", 0600);
2402
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2403
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2404
		}
2405
	}
2406

    
2407
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2408
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2409
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2410
}
2411
?>
(2-2/61)