Project

General

Profile

Download (70.9 KB) Statistics
| Branch: | Tag: | Revision:
1 55eb9c44 --global
<?php
2 b37b4034 Phil Davis
/*
3 ac24dc24 Renato Botelho
 * auth.inc
4 995df6c3 Stephen Beaver
 *
5 ac24dc24 Renato Botelho
 * 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 38809d47 Renato Botelho do Couto
 * Copyright (c) 2004-2013 BSD Perimeter
10
 * Copyright (c) 2013-2016 Electric Sheep Fencing
11 8f585441 Luiz Souza
 * Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
12 ac24dc24 Renato Botelho
 * All rights reserved.
13 995df6c3 Stephen Beaver
 *
14 b12ea3fb Renato Botelho
 * 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 995df6c3 Stephen Beaver
 *
18 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
19 995df6c3 Stephen Beaver
 *
20 b12ea3fb Renato Botelho
 * 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 995df6c3 Stephen Beaver
 */
26 ac24dc24 Renato Botelho
27 55eb9c44 --global
/*
28
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
29
 * file courtesy of Michael Retterklieber.
30
 */
31 82cd6022 PiBa-NL
include_once('phpsessionmanager.inc');
32 1e0b1727 Phil Davis
if (!$do_not_include_config_gui_inc) {
33 052e65ef Scott Ullrich
	require_once("config.gui.inc");
34 1e0b1727 Phil Davis
}
35 55eb9c44 --global
36 9ae11a62 Scott Ullrich
// Will be changed to false if security checks fail
37
$security_passed = true;
38
39 1180e4f0 Sjon Hortensius
/* If this function doesn't exist, we're being called from Captive Portal or
40 0321fa1b jim-p
   another internal subsystem which does not include authgui.inc */
41 cc9b0f76 jim-p
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 9146639e jim-p
	$entries = array();
47 555a9ab5 jim-p
	exec("/sbin/pfctl -t 'sshguard' -T show", $entries);
48 cc9b0f76 jim-p
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 ef094bef Renato Botelho do Couto
			$retval = pfSense_kill_states(utf8_encode($_SERVER['REMOTE_ADDR']));
56 cc9b0f76 jim-p
			if (is_ipaddrv4($_SERVER['REMOTE_ADDR'])) {
57 ef094bef Renato Botelho do Couto
				$retval = pfSense_kill_states("0.0.0.0/0", utf8_encode($_SERVER['REMOTE_ADDR']));
58 cc9b0f76 jim-p
			} elseif (is_ipaddrv6($_SERVER['REMOTE_ADDR'])) {
59 ef094bef Renato Botelho do Couto
				$retval = pfSense_kill_states("::", utf8_encode($_SERVER['REMOTE_ADDR']));
60 cc9b0f76 jim-p
			}
61
			exit;
62
		}
63
		$security_passed = false;
64
	}
65
}
66
67 14eab6fb jim-p
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
68 0734024c Chris Buechler
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
69 0321fa1b jim-p
	$found_host = false;
70 209620ea Seth Mos
71 4cf79fdd smos
	/* Either a IPv6 address with or without a alternate port */
72 1e0b1727 Phil Davis
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
73 4cf79fdd smos
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
74 209620ea Seth Mos
		/* v6 address has more parts, drop the last part */
75 1e0b1727 Phil Davis
		if (count($http_host_port) > 1) {
76 209620ea Seth Mos
			array_pop($http_host_port);
77
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
78
		} else {
79 4cf79fdd smos
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
80 209620ea Seth Mos
		}
81 7319dc73 jim-p
	} else {
82 4fcab77b smos
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
83
		$http_host = $http_host[0];
84 7319dc73 jim-p
	}
85 1e0b1727 Phil Davis
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
86 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
87 9ae11a62 Scott Ullrich
		$found_host = true;
88 1e0b1727 Phil Davis
	}
89
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
90 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
91 d7bf3178 Erik Fonnesbeck
		$found_host = true;
92 1e0b1727 Phil Davis
	}
93 9ae11a62 Scott Ullrich
94 1e0b1727 Phil Davis
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
95
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
96
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
97 0321fa1b jim-p
				$found_host = true;
98 9ae11a62 Scott Ullrich
				break;
99
			}
100 1e0b1727 Phil Davis
		}
101
	}
102 7319dc73 jim-p
103 1e0b1727 Phil Davis
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
104
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
105
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
106 fa087612 jim-p
				$found_host = true;
107
				break;
108
			}
109 1e0b1727 Phil Davis
		}
110
	}
111 fa087612 jim-p
112 1e0b1727 Phil Davis
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
113 86b21903 jim-p
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
114 1e0b1727 Phil Davis
		foreach ($althosts as $ah) {
115
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
116 86b21903 jim-p
				$found_host = true;
117 9ae11a62 Scott Ullrich
				break;
118
			}
119 1e0b1727 Phil Davis
		}
120 9b13f84b Scott Ullrich
	}
121 ce46b5da Scott Ullrich
122 1e0b1727 Phil Davis
	if ($found_host == false) {
123
		if (!security_checks_disabled()) {
124 8cd558b6 ayvis
			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 9ae11a62 Scott Ullrich
			exit;
126
		}
127
		$security_passed = false;
128
	}
129
}
130 ef173724 Scott Ullrich
131 9ae11a62 Scott Ullrich
// If the HTTP_REFERER is something other than ourselves then disallow.
132 1e0b1727 Phil Davis
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 9ae11a62 Scott Ullrich
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
137
				header("Refresh: 1; url=index.php");
138 1180e4f0 Sjon Hortensius
?>
139
<!DOCTYPE html>
140
<html lang="en">
141
<head>
142 b4738ddc NewEraCracker
	<link rel="stylesheet" href="/css/pfSense.css" />
143 1180e4f0 Sjon Hortensius
	<title><?=gettext("Redirecting..."); ?></title>
144
</head>
145
<body id="error" class="no-menu">
146
	<div id="jumbotron">
147
		<div class="container">
148 c7d61071 Sander van Leeuwen
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
149
				<p><?=gettext("Redirecting to the dashboard...")?></p>
150
			</div>
151 1180e4f0 Sjon Hortensius
		</div>
152
	</div>
153
</body>
154
</html>
155
<?php
156 9ae11a62 Scott Ullrich
				exit;
157
			}
158
		}
159
		$found_host = false;
160
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
161 e6f7e0be smos
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
162 1e0b1727 Phil Davis
		if ($referrer_host) {
163 ae52d165 Renato Botelho
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
164 4e322e2c Phil Davis
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
165 9ae11a62 Scott Ullrich
				$found_host = true;
166 1e0b1727 Phil Davis
			}
167 9f0bee02 jim-p
168 1e0b1727 Phil Davis
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
169 9ae11a62 Scott Ullrich
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
170
				foreach ($althosts as $ah) {
171 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ah) == 0) {
172 9ae11a62 Scott Ullrich
						$found_host = true;
173
						break;
174
					}
175
				}
176
			}
177 9f0bee02 jim-p
178 1e0b1727 Phil Davis
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
179
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
180
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
181 9f0bee02 jim-p
						$found_host = true;
182
						break;
183
					}
184 1e0b1727 Phil Davis
				}
185
			}
186 9f0bee02 jim-p
187 1e0b1727 Phil Davis
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
188
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
189
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
190 9f0bee02 jim-p
						$found_host = true;
191
						break;
192
					}
193 1e0b1727 Phil Davis
				}
194
			}
195 9f0bee02 jim-p
196 1e0b1727 Phil Davis
			if (!$found_host) {
197 9ae11a62 Scott Ullrich
				$interface_list_ips = get_configured_ip_addresses();
198 1e0b1727 Phil Davis
				foreach ($interface_list_ips as $ilips) {
199
					if (strcasecmp($referrer_host, $ilips) == 0) {
200 9ae11a62 Scott Ullrich
						$found_host = true;
201
						break;
202
					}
203
				}
204 6a53de6f NewEraCracker
				$interface_list_ipv6s = get_configured_ipv6_addresses(true);
205 1e0b1727 Phil Davis
				foreach ($interface_list_ipv6s as $ilipv6s) {
206 6a53de6f NewEraCracker
					$ilipv6s = explode('%', $ilipv6s)[0];
207 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
208 e6f7e0be smos
						$found_host = true;
209
						break;
210
					}
211
				}
212 1e0b1727 Phil Davis
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
213 17dd7ff3 Chris Buechler
					// allow SSH port forwarded connections and links from localhost
214
					$found_host = true;
215
				}
216 9ae11a62 Scott Ullrich
			}
217 5b93a1f4 jim-p
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 9ae11a62 Scott Ullrich
		}
234 1e0b1727 Phil Davis
		if ($found_host == false) {
235
			if (!security_checks_disabled()) {
236 530e4707 NOYB
				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 0f806eca Erik Fonnesbeck
				exit;
238
			}
239 9ae11a62 Scott Ullrich
			$security_passed = false;
240
		}
241 1e0b1727 Phil Davis
	} else {
242 9ae11a62 Scott Ullrich
		$security_passed = false;
243 1e0b1727 Phil Davis
	}
244 4fe9c2dc Scott Ullrich
}
245
246 1e0b1727 Phil Davis
if (function_exists("display_error_form") && $security_passed) {
247 9ae11a62 Scott Ullrich
	/* Security checks passed, so it should be OK to turn them back on */
248
	restore_security_checks();
249 1e0b1727 Phil Davis
}
250 9ae11a62 Scott Ullrich
unset($security_passed);
251
252 55eb9c44 --global
$groupindex = index_groups();
253
$userindex = index_users();
254
255
function index_groups() {
256
	global $g, $debug, $config, $groupindex;
257
258
	$groupindex = array();
259
260 6dcd80af Ermal
	if (is_array($config['system']['group'])) {
261 55eb9c44 --global
		$i = 0;
262 1e0b1727 Phil Davis
		foreach ($config['system']['group'] as $groupent) {
263 55eb9c44 --global
			$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 6dcd80af Ermal
	if (is_array($config['system']['user'])) {
275 55eb9c44 --global
		$i = 0;
276 1e0b1727 Phil Davis
		foreach ($config['system']['user'] as $userent) {
277 55eb9c44 --global
			$userindex[$userent['name']] = $i;
278
			$i++;
279
		}
280
	}
281
282
	return ($userindex);
283
}
284
285
function & getUserEntry($name) {
286
	global $debug, $config, $userindex;
287 0ef6fddc jim-p
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
288
289 1e0b1727 Phil Davis
	if (isset($userindex[$name])) {
290 55eb9c44 --global
		return $config['system']['user'][$userindex[$name]];
291 0ef6fddc jim-p
	} elseif ($authcfg['type'] != "Local Database") {
292
		$user = array();
293
		$user['name'] = $name;
294
		return $user;
295 1e0b1727 Phil Davis
	}
296 55eb9c44 --global
}
297
298
function & getUserEntryByUID($uid) {
299
	global $debug, $config;
300 84924e76 Ermal
301 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
302
		foreach ($config['system']['user'] as & $user) {
303
			if ($user['uid'] == $uid) {
304 84924e76 Ermal
				return $user;
305 1e0b1727 Phil Davis
			}
306
		}
307
	}
308 55eb9c44 --global
309
	return false;
310
}
311
312
function & getGroupEntry($name) {
313
	global $debug, $config, $groupindex;
314 1e0b1727 Phil Davis
	if (isset($groupindex[$name])) {
315 55eb9c44 --global
		return $config['system']['group'][$groupindex[$name]];
316 1e0b1727 Phil Davis
	}
317 55eb9c44 --global
}
318
319
function & getGroupEntryByGID($gid) {
320
	global $debug, $config;
321 84924e76 Ermal
322 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
323
		foreach ($config['system']['group'] as & $group) {
324
			if ($group['gid'] == $gid) {
325 84924e76 Ermal
				return $group;
326 1e0b1727 Phil Davis
			}
327
		}
328
	}
329 55eb9c44 --global
330
	return false;
331
}
332
333 6dc88d53 Ermal Luci
function get_user_privileges(& $user) {
334 7abc3f99 Phil Davis
	global $config, $_SESSION;
335 0ef6fddc jim-p
336
	$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
337 4de15854 jim-p
	$allowed_groups = array();
338 6dc88d53 Ermal Luci
339 1e0b1727 Phil Davis
	$privs = $user['priv'];
340
	if (!is_array($privs)) {
341
		$privs = array();
342
	}
343 6dc88d53 Ermal Luci
344 7abc3f99 Phil Davis
	// 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 0ef6fddc jim-p
	if ($authcfg['type'] == "ldap") {
352 7abc3f99 Phil Davis
		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 0ef6fddc jim-p
	} elseif ($authcfg['type'] == "radius") {
361 7abc3f99 Phil Davis
		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 0ef6fddc jim-p
	}
370
371 7abc3f99 Phil Davis
	if (empty($allowed_groups)) {
372
		$allowed_groups = local_user_get_groups($user, true);
373 0ef6fddc jim-p
	}
374 6dc88d53 Ermal Luci
375 4de15854 jim-p
	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 1e0b1727 Phil Davis
		}
386
	}
387 6dc88d53 Ermal Luci
388 1e0b1727 Phil Davis
	return $privs;
389 6dc88d53 Ermal Luci
}
390
391
function userHasPrivilege($userent, $privid = false) {
392 fa0ed29e jim-p
	global $config;
393 6dc88d53 Ermal Luci
394 1e0b1727 Phil Davis
	if (!$privid || !is_array($userent)) {
395
		return false;
396
	}
397 6dc88d53 Ermal Luci
398 1e0b1727 Phil Davis
	$privs = get_user_privileges($userent);
399 6dc88d53 Ermal Luci
400 1e0b1727 Phil Davis
	if (!is_array($privs)) {
401
		return false;
402
	}
403 6dc88d53 Ermal Luci
404 1e0b1727 Phil Davis
	if (!in_array($privid, $privs)) {
405
		return false;
406
	}
407 6dc88d53 Ermal Luci
408 fa0ed29e jim-p
	/* 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 1e0b1727 Phil Davis
	return true;
421 6dc88d53 Ermal Luci
}
422
423 55eb9c44 --global
function local_backed($username, $passwd) {
424
425
	$user = getUserEntry($username);
426 1e0b1727 Phil Davis
	if (!$user) {
427 55eb9c44 --global
		return false;
428 1e0b1727 Phil Davis
	}
429 55eb9c44 --global
430 1e0b1727 Phil Davis
	if (is_account_disabled($username) || is_account_expired($username)) {
431 a13ce628 Ermal Lu?i
		return false;
432 1e0b1727 Phil Davis
	}
433 a13ce628 Ermal Lu?i
434 9219378b daniel
	if ($user['bcrypt-hash']) {
435
		if (password_verify($passwd, $user['bcrypt-hash'])) {
436
			return true;
437
		}
438
	}
439
440
	//for backwards compatibility
441 1e0b1727 Phil Davis
	if ($user['password']) {
442
		if (crypt($passwd, $user['password']) == $user['password']) {
443 55eb9c44 --global
			return true;
444 1e0b1727 Phil Davis
		}
445 55eb9c44 --global
	}
446
447 1e0b1727 Phil Davis
	if ($user['md5-hash']) {
448
		if (md5($passwd) == $user['md5-hash']) {
449 55eb9c44 --global
			return true;
450 1e0b1727 Phil Davis
		}
451 55eb9c44 --global
	}
452
453
	return false;
454
}
455
456 79f7bc7f Renato Botelho
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 f9ed5d57 James Webb
		if ($user['uid'] > 65000) {
466
			continue;
467
		} else if ($user['uid'] < 2000 && !in_array($user, $u2add)) {
468 79f7bc7f Renato Botelho
			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 90510875 Renato Botelho
				log_error("Removing user: {$user['name']}");
489 79f7bc7f Renato Botelho
				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 90510875 Renato Botelho
				log_error("Removing group: {$group['name']}");
511 79f7bc7f Renato Botelho
				unset($config['system']['group'][$i]);
512
				break;
513
			}
514
		}
515
	}
516
517
	foreach ($u2add as $user) {
518 90510875 Renato Botelho
		log_error("Adding user: {$user['name']}");
519 79f7bc7f Renato Botelho
		$config['system']['user'][] = $user;
520
	}
521
522
	foreach ($g2add as $group) {
523 90510875 Renato Botelho
		log_error("Adding group: {$group['name']}");
524 79f7bc7f Renato Botelho
		$config['system']['group'][] = $group;
525
	}
526
527 dc3bc1f8 Renato Botelho
	/* 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 79f7bc7f Renato Botelho
	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 55eb9c44 --global
	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 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
558 3ee1e659 Renato Botelho
			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 1e0b1727 Phil Davis
			}
569 2b41df9c Renato Botelho
			/*
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 0a39f78f jim-p
			$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($line[0]);
575 1e0b1727 Phil Davis
			if ($debug) {
576 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
577 1e0b1727 Phil Davis
			}
578 55eb9c44 --global
			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 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
589 1e0b1727 Phil Davis
			if (!strncmp($line[0], "_", 1)) {
590 55eb9c44 --global
				continue;
591 1e0b1727 Phil Davis
			}
592
			if ($line[2] < 2000) {
593 55eb9c44 --global
				continue;
594 1e0b1727 Phil Davis
			}
595
			if ($line[2] > 65000) {
596 55eb9c44 --global
				continue;
597 1e0b1727 Phil Davis
			}
598 0a39f78f jim-p
			$cmd = "/usr/sbin/pw groupdel -g " . escapeshellarg($line[2]);
599 1e0b1727 Phil Davis
			if ($debug) {
600 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
601 1e0b1727 Phil Davis
			}
602 55eb9c44 --global
			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 5af2baf7 jim-p
	/* sync all local users */
612 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
613
		foreach ($config['system']['user'] as $user) {
614 5af2baf7 jim-p
			local_user_set($user);
615 1e0b1727 Phil Davis
		}
616
	}
617 5af2baf7 jim-p
618 f3e0a111 jim-p
	/* sync all local groups */
619 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
620
		foreach ($config['system']['group'] as $group) {
621 f3e0a111 jim-p
			local_group_set($group);
622 1e0b1727 Phil Davis
		}
623
	}
624 55eb9c44 --global
}
625
626
function local_user_set(& $user) {
627
	global $g, $debug;
628
629 9219378b daniel
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
630 530e4707 NOYB
		log_error("There is something wrong in the config because user {$user['name']} password is missing!");
631 b3c106a0 Ermal
		return;
632
	}
633
634 2bb07efc Scott Ullrich
635 1180e4f0 Sjon Hortensius
	$home_base = "/home/";
636 55eb9c44 --global
	$user_uid = $user['uid'];
637
	$user_name = $user['name'];
638 461df7c0 jim-p
	$user_home = "{$home_base}{$user_name}";
639 55eb9c44 --global
	$user_shell = "/etc/rc.initial";
640
	$user_group = "nobody";
641
642
	// Ensure $home_base exists and is writable
643 1e0b1727 Phil Davis
	if (!is_dir($home_base)) {
644 55eb9c44 --global
		mkdir($home_base, 0755);
645 1e0b1727 Phil Davis
	}
646 55eb9c44 --global
647 df8d74de jim-p
	$lock_account = false;
648 55eb9c44 --global
	/* configure shell type */
649 3e251b12 Erik Fonnesbeck
	/* Cases here should be ordered by most privileged to least privileged. */
650 a137fedd jim-p
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
651 29293dce jim-p
		$user_shell = "/bin/tcsh";
652 74fd2299 doktornotor
	} elseif (userHasPrivilege($user, "user-copy-files-chroot")) {
653
		$user_shell = "/usr/local/sbin/scponlyc";
654 647db6bb doktornotor
	} elseif (userHasPrivilege($user, "user-copy-files")) {
655
		$user_shell = "/usr/local/bin/scponly";
656 3e251b12 Erik Fonnesbeck
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
657
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
658 fbfd675a jim-p
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
659
		$user_shell = "/sbin/nologin";
660 1ed86bc6 jim-p
	} else {
661
		$user_shell = "/sbin/nologin";
662 df8d74de jim-p
		$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 55eb9c44 --global
	}
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 1e0b1727 Phil Davis
		if ($debug) {
675 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Running: %s"), $cmd));
676 1e0b1727 Phil Davis
		}
677 55eb9c44 --global
		$fd = popen($cmd, "w");
678 9219378b daniel
		if (empty($user['bcrypt-hash'])) {
679
			fwrite($fd, $user['password']);
680 9a7911eb Daniel Vinakovsky
		} else {
681 9219378b daniel
			fwrite($fd, $user['bcrypt-hash']);
682
		}
683 55eb9c44 --global
		pclose($fd);
684
		$user_group = "wheel";
685 2708e399 jim-p
		$user_home = "/root";
686 29293dce jim-p
		$user_shell = "/etc/rc.initial";
687 55eb9c44 --global
	}
688
689
	/* read from pw db */
690 9fd14591 jim-p
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
691 55eb9c44 --global
	$pwread = fgets($fd);
692
	pclose($fd);
693 9fd14591 jim-p
	$userattrs = explode(":", trim($pwread));
694 55eb9c44 --global
695 13a70e7d Renato Botelho
	$skel_dir = '/etc/skel';
696
697 55eb9c44 --global
	/* determine add or mod */
698 9fd14591 jim-p
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
699 4bf17edc jim-p
		$user_op = "useradd -m -k " . escapeshellarg($skel_dir) . " -o";
700 38564fde smos
	} else {
701 55eb9c44 --global
		$user_op = "usermod";
702 38564fde smos
	}
703 55eb9c44 --global
704 1180e4f0 Sjon Hortensius
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
705 55eb9c44 --global
	/* add or mod pw db */
706 0a39f78f jim-p
	$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 55eb9c44 --global
715 1e0b1727 Phil Davis
	if ($debug) {
716 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
717 1e0b1727 Phil Davis
	}
718 55eb9c44 --global
	$fd = popen($cmd, "w");
719 9219378b daniel
	if (empty($user['bcrypt-hash'])) {
720
		fwrite($fd, $user['password']);
721 9a7911eb Daniel Vinakovsky
	} else {
722 9219378b daniel
		fwrite($fd, $user['bcrypt-hash']);
723
	}
724 55eb9c44 --global
	pclose($fd);
725
726
	/* create user directory if required */
727
	if (!is_dir($user_home)) {
728
		mkdir($user_home, 0700);
729
	}
730 23c652cd Ermal
	@chown($user_home, $user_name);
731
	@chgrp($user_home, $user_group);
732 55eb9c44 --global
733 13a70e7d Renato Botelho
	/* 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 55eb9c44 --global
	/* write out ssh authorized key file */
742 1e0b1727 Phil Davis
	if ($user['authorizedkeys']) {
743 a2286360 Ermal Lu?i
		if (!is_dir("{$user_home}/.ssh")) {
744 23c652cd Ermal
			@mkdir("{$user_home}/.ssh", 0700);
745
			@chown("{$user_home}/.ssh", $user_name);
746 a2286360 Ermal Lu?i
		}
747
		$keys = base64_decode($user['authorizedkeys']);
748 23c652cd Ermal
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
749
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
750 1e0b1727 Phil Davis
	} else {
751 cdab65cc Erik Fonnesbeck
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
752 1e0b1727 Phil Davis
	}
753 df8d74de jim-p
754
	$un = $lock_account ? "" : "un";
755 0a39f78f jim-p
	exec("/usr/sbin/pw {$un}lock " . escapeshellarg($user_name) . " -q 2>/dev/null");
756 1180e4f0 Sjon Hortensius
757 55eb9c44 --global
}
758
759
function local_user_del($user) {
760
	global $debug;
761 2bb07efc Scott Ullrich
762 55eb9c44 --global
	/* remove all memberships */
763 019e6c3f jim-p
	local_user_set_groups($user);
764 55eb9c44 --global
765 a39675ec jim-p
	/* Don't remove /root */
766 1e0b1727 Phil Davis
	if ($user['uid'] != 0) {
767 a39675ec jim-p
		$rmhome = "-r";
768 1e0b1727 Phil Davis
	}
769 a39675ec jim-p
770 9fd14591 jim-p
	/* 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 55eb9c44 --global
	/* delete from pw db */
782 0a39f78f jim-p
	$cmd = "/usr/sbin/pw userdel -n " . escapeshellarg($user['name']) . " " . escapeshellarg($rmhome);
783 55eb9c44 --global
784 1e0b1727 Phil Davis
	if ($debug) {
785 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
786 1e0b1727 Phil Davis
	}
787 0914b6bb Ermal
	mwexec($cmd);
788 2bb07efc Scott Ullrich
789 0914b6bb Ermal
	/* Delete user from groups needs a call to write_config() */
790
	local_group_del_user($user);
791 55eb9c44 --global
}
792
793 4d9801c2 Jim Thompson
function local_user_set_password(&$user, $password) {
794 f9ed5d57 James Webb
	global $config;
795
796 33386b07 Daniel Vinakovsky
	unset($user['password']);
797
	unset($user['md5-hash']);
798
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
799 f9ed5d57 James Webb
	if (($user['name'] == $config['hasync']['username']) &&
800
	    ($config['hasync']['adminsync'] == 'on')) {
801
		$config['hasync']['new_password'] = $password;
802
	}
803 55eb9c44 --global
}
804
805
function local_user_get_groups($user, $all = false) {
806
	global $debug, $config;
807
808
	$groups = array();
809 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
810 55eb9c44 --global
		return $groups;
811 1e0b1727 Phil Davis
	}
812 55eb9c44 --global
813 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
814 4de8f7ba Phil Davis
		if ($all || (!$all && ($group['name'] != "all"))) {
815 1e0b1727 Phil Davis
			if (is_array($group['member'])) {
816
				if (in_array($user['uid'], $group['member'])) {
817 55eb9c44 --global
					$groups[] = $group['name'];
818 1e0b1727 Phil Davis
				}
819
			}
820
		}
821
	}
822 55eb9c44 --global
823 1e0b1727 Phil Davis
	if ($all) {
824 b0c231e4 jim-p
		$groups[] = "all";
825 1e0b1727 Phil Davis
	}
826 b0c231e4 jim-p
827 55eb9c44 --global
	sort($groups);
828
829
	return $groups;
830 1180e4f0 Sjon Hortensius
831 55eb9c44 --global
}
832
833 4de8f7ba Phil Davis
function local_user_set_groups($user, $new_groups = NULL) {
834 aa029c93 Renato Botelho
	global $debug, $config, $groupindex, $userindex;
835 4de8f7ba Phil Davis
836 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
837 55eb9c44 --global
		return;
838 1e0b1727 Phil Davis
	}
839 55eb9c44 --global
840 739c78ac jim-p
	$cur_groups = local_user_get_groups($user, true);
841 55eb9c44 --global
	$mod_groups = array();
842
843 1e0b1727 Phil Davis
	if (!is_array($new_groups)) {
844 55eb9c44 --global
		$new_groups = array();
845 1e0b1727 Phil Davis
	}
846 55eb9c44 --global
847 1e0b1727 Phil Davis
	if (!is_array($cur_groups)) {
848 55eb9c44 --global
		$cur_groups = array();
849 1e0b1727 Phil Davis
	}
850 55eb9c44 --global
851
	/* determine which memberships to add */
852
	foreach ($new_groups as $groupname) {
853 4de8f7ba Phil Davis
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
854 55eb9c44 --global
			continue;
855 1e0b1727 Phil Davis
		}
856 c6c398c6 jim-p
		$group = &$config['system']['group'][$groupindex[$groupname]];
857 55eb9c44 --global
		$group['member'][] = $user['uid'];
858
		$mod_groups[] = $group;
859 aa029c93 Renato Botelho
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 55eb9c44 --global
	}
868 9ae11a62 Scott Ullrich
	unset($group);
869 55eb9c44 --global
870
	/* determine which memberships to remove */
871
	foreach ($cur_groups as $groupname) {
872 4de8f7ba Phil Davis
		if (in_array($groupname, $new_groups)) {
873 e879fc81 Ermal
			continue;
874 1e0b1727 Phil Davis
		}
875
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
876 25fec9b3 jim-p
			continue;
877 1e0b1727 Phil Davis
		}
878 c6c398c6 jim-p
		$group = &$config['system']['group'][$groupindex[$groupname]];
879 7b5c56ea jim-p
		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 55eb9c44 --global
	}
885 9ae11a62 Scott Ullrich
	unset($group);
886 55eb9c44 --global
887
	/* sync all modified groups */
888 1e0b1727 Phil Davis
	foreach ($mod_groups as $group) {
889 55eb9c44 --global
		local_group_set($group);
890 1e0b1727 Phil Davis
	}
891 55eb9c44 --global
}
892
893 0914b6bb Ermal
function local_group_del_user($user) {
894
	global $config;
895
896 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
897
		return;
898
	}
899 0914b6bb Ermal
900 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
901 0914b6bb Ermal
		if (is_array($group['member'])) {
902
			foreach ($group['member'] as $idx => $uid) {
903 1e0b1727 Phil Davis
				if ($user['uid'] == $uid) {
904 0914b6bb Ermal
					unset($config['system']['group']['member'][$idx]);
905 1e0b1727 Phil Davis
				}
906 0914b6bb Ermal
			}
907
		}
908
	}
909
}
910
911 55eb9c44 --global
function local_group_set($group, $reset = false) {
912
	global $debug;
913
914
	$group_name = $group['name'];
915
	$group_gid = $group['gid'];
916 baca968c Ermal
	$group_members = '';
917 64fa4207 Steve Beaver
918 1e0b1727 Phil Davis
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
919 4de8f7ba Phil Davis
		$group_members = implode(",", $group['member']);
920 1e0b1727 Phil Davis
	}
921 55eb9c44 --global
922 64fa4207 Steve Beaver
	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 baca968c Ermal
		return;
930 1e0b1727 Phil Davis
	}
931 baca968c Ermal
932 55eb9c44 --global
	/* determine add or mod */
933 0a39f78f jim-p
	if (mwexec("/usr/sbin/pw groupshow -g " . escapeshellarg($group_gid) . " 2>&1", true) == 0) {
934 7cb01159 Chris Buechler
		$group_op = "groupmod -l";
935 1e0b1727 Phil Davis
	} else {
936 7cb01159 Chris Buechler
		$group_op = "groupadd -n";
937 1e0b1727 Phil Davis
	}
938 55eb9c44 --global
939
	/* add or mod group db */
940 0a39f78f jim-p
	$cmd = "/usr/sbin/pw {$group_op} " .
941
		escapeshellarg($group_name) .
942
		" -g " . escapeshellarg($group_gid) .
943
		" -M " . escapeshellarg($group_members) . " 2>&1";
944 55eb9c44 --global
945 1e0b1727 Phil Davis
	if ($debug) {
946 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
947 1e0b1727 Phil Davis
	}
948 55eb9c44 --global
949 64fa4207 Steve Beaver
	mwexec($cmd);
950 55eb9c44 --global
}
951
952
function local_group_del($group) {
953
	global $debug;
954
955
	/* delete from group db */
956 0a39f78f jim-p
	$cmd = "/usr/sbin/pw groupdel " . escapeshellarg($group['name']);
957 55eb9c44 --global
958 1e0b1727 Phil Davis
	if ($debug) {
959 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
960 1e0b1727 Phil Davis
	}
961 0914b6bb Ermal
	mwexec($cmd);
962 55eb9c44 --global
}
963
964 6306b5dd Ermal Lu?i
function ldap_test_connection($authcfg) {
965 c61e4626 Ermal Lu?i
	if ($authcfg) {
966 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
967 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
968 d672403c derelict-pf
		} else {
969
			$ldapproto = "ldap";
970 1e0b1727 Phil Davis
		}
971
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
972
		$ldapport = $authcfg['ldap_port'];
973
		if (!empty($ldapport)) {
974 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
975 1e0b1727 Phil Davis
		}
976
	} else {
977 6306b5dd Ermal Lu?i
		return false;
978 1e0b1727 Phil Davis
	}
979 55eb9c44 --global
980 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
981 4de8f7ba Phil Davis
	if (!$ldapserver) {
982 1e0b1727 Phil Davis
		return false;
983
	}
984 c61e4626 Ermal Lu?i
985 1e0b1727 Phil Davis
	/* connect and see if server is up */
986
	$error = false;
987
	if (!($ldap = ldap_connect($ldapserver))) {
988 9f27de6d jim-p
		$error = true;
989 1e0b1727 Phil Davis
	}
990 c61e4626 Ermal Lu?i
991 1e0b1727 Phil Davis
	if ($error == true) {
992 34925626 Phil Davis
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $authcfg['name']));
993 1e0b1727 Phil Davis
		return false;
994
	}
995 55eb9c44 --global
996 b0c7d642 jim-p
	/* Setup CA environment if needed. */
997
	ldap_setup_caenv($ldap, $authcfg);
998
999 55eb9c44 --global
	return true;
1000
}
1001
1002 996a1ad9 jim-p
function ldap_setup_caenv($ldap, $authcfg) {
1003 fe2031ab Ermal
	global $g;
1004 007e59d2 jim-p
	require_once("certs.inc");
1005 fe2031ab Ermal
1006
	unset($caref);
1007 d672403c derelict-pf
	if (empty($authcfg['ldap_caref']) || strstr($authcfg['ldap_urltype'], "Standard")) {
1008 b0c7d642 jim-p
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
1009 fe2031ab Ermal
		return;
1010 87c67243 jim-p
	} elseif ($authcfg['ldap_caref'] == "global") {
1011 39f48832 jim-p
		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 b0c7d642 jim-p
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1014 fe2031ab Ermal
	} else {
1015 a7702ed5 Ermal
		$caref = lookup_ca($authcfg['ldap_caref']);
1016 39f48832 jim-p
		$cert_details = openssl_x509_parse(base64_decode($caref['crt']));
1017 ff500c90 jim-p
		$param = array('caref' => $authcfg['ldap_caref']);
1018
		$cachain = ca_chain($param);
1019 fe2031ab Ermal
		if (!$caref) {
1020 a7702ed5 Ermal
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
1021 fe2031ab Ermal
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
1022 b0c7d642 jim-p
			ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1023 fe2031ab Ermal
			return;
1024
		}
1025 996a1ad9 jim-p
1026 22d6b2c4 jim-p
		$cert_path = "{$g['varrun_path']}/certs";
1027 39f48832 jim-p
		$cert_filename = "{$cert_path}/{$cert_details['hash']}.0";
1028 996a1ad9 jim-p
		safe_mkdir($cert_path);
1029 39f48832 jim-p
		unlink_if_exists($cert_filename);
1030
		file_put_contents($cert_filename, $cachain);
1031
		@chmod($cert_filename, 0600);
1032 996a1ad9 jim-p
1033 b0c7d642 jim-p
		ldap_set_option($ldap, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_HARD);
1034 39f48832 jim-p
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR, $cert_path);
1035
		ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, $cert_filename);
1036 fe2031ab Ermal
	}
1037
}
1038
1039 6306b5dd Ermal Lu?i
function ldap_test_bind($authcfg) {
1040 55eb9c44 --global
	global $debug, $config, $g;
1041
1042 c61e4626 Ermal Lu?i
	if ($authcfg) {
1043 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1044 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1045 d672403c derelict-pf
		} else {
1046
			$ldapproto = "ldap";
1047 1e0b1727 Phil Davis
		}
1048
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1049
		$ldapport = $authcfg['ldap_port'];
1050
		if (!empty($ldapport)) {
1051 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1052 1e0b1727 Phil Davis
		}
1053
		$ldapbasedn = $authcfg['ldap_basedn'];
1054
		$ldapbindun = $authcfg['ldap_binddn'];
1055
		$ldapbindpw = $authcfg['ldap_bindpw'];
1056
		$ldapver = $authcfg['ldap_protver'];
1057 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1058 b310666c Carl P. Corliss
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1059 1e0b1727 Phil Davis
			$ldapanon = true;
1060
		} else {
1061
			$ldapanon = false;
1062
		}
1063
	} else {
1064 6306b5dd Ermal Lu?i
		return false;
1065 1e0b1727 Phil Davis
	}
1066 c61e4626 Ermal Lu?i
1067
	/* first check if there is even an LDAP server populated */
1068 1e0b1727 Phil Davis
	if (!$ldapserver) {
1069
		return false;
1070
	}
1071 c61e4626 Ermal Lu?i
1072 1e0b1727 Phil Davis
	/* connect and see if server is up */
1073
	$error = false;
1074
	if (!($ldap = ldap_connect($ldapserver))) {
1075 9f27de6d jim-p
		$error = true;
1076 1e0b1727 Phil Davis
	}
1077 c61e4626 Ermal Lu?i
1078 1e0b1727 Phil Davis
	if ($error == true) {
1079
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1080
		return false;
1081
	}
1082 55eb9c44 --global
1083 b0c7d642 jim-p
	/* Setup CA environment if needed. */
1084
	ldap_setup_caenv($ldap, $authcfg);
1085
1086 55eb9c44 --global
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1087 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1088 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1089 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1090
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1091 1180e4f0 Sjon Hortensius
1092 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1093 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1094 d672403c derelict-pf
			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 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1101
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1102 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1103 6306b5dd Ermal Lu?i
		if (!($res = @ldap_bind($ldap))) {
1104
			@ldap_close($ldap);
1105 c61e4626 Ermal Lu?i
			return false;
1106 6306b5dd Ermal Lu?i
		}
1107
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1108
		@ldap_close($ldap);
1109 55eb9c44 --global
		return false;
1110 6306b5dd Ermal Lu?i
	}
1111 55eb9c44 --global
1112 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1113 c61e4626 Ermal Lu?i
1114 55eb9c44 --global
	return true;
1115
}
1116
1117 6306b5dd Ermal Lu?i
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
1118 55eb9c44 --global
	global $debug, $config, $g;
1119
1120 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1121 55eb9c44 --global
		return;
1122 1e0b1727 Phil Davis
	}
1123 55eb9c44 --global
1124 7a938f1b Ermal
	$ous = array();
1125
1126 c61e4626 Ermal Lu?i
	if ($authcfg) {
1127 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1128 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1129 d672403c derelict-pf
		} else {
1130
			$ldapproto = "ldap";
1131 1e0b1727 Phil Davis
		}
1132
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1133
		$ldapport = $authcfg['ldap_port'];
1134
		if (!empty($ldapport)) {
1135 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1136 1e0b1727 Phil Davis
		}
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 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1150 1e0b1727 Phil Davis
	} else {
1151 6306b5dd Ermal Lu?i
		return false;
1152 1e0b1727 Phil Davis
	}
1153 55eb9c44 --global
1154 1e0b1727 Phil Davis
	/* 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 c61e4626 Ermal Lu?i
1160
	/* connect and see if server is up */
1161 1e0b1727 Phil Davis
	$error = false;
1162
	if (!($ldap = ldap_connect($ldapserver))) {
1163 9f27de6d jim-p
		$error = true;
1164 1e0b1727 Phil Davis
	}
1165 c61e4626 Ermal Lu?i
1166 1e0b1727 Phil Davis
	if ($error == true) {
1167
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1168
		return $ous;
1169
	}
1170 c61e4626 Ermal Lu?i
1171 b0c7d642 jim-p
	/* Setup CA environment if needed. */
1172
	ldap_setup_caenv($ldap, $authcfg);
1173
1174 c61e4626 Ermal Lu?i
	$ldapfilter = "(|(ou=*)(cn=Users))";
1175 55eb9c44 --global
1176
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1177 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1178 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1179 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1180
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1181 55eb9c44 --global
1182 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1183 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1184 d672403c derelict-pf
			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 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1191
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1192 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1193 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1194 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
1195 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1196 1e0b1727 Phil Davis
			return $ous;
1197 c61e4626 Ermal Lu?i
		}
1198
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1199 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
1200 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1201 c61e4626 Ermal Lu?i
		return $ous;
1202 55eb9c44 --global
	}
1203
1204 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1205 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_list";
1206 1e0b1727 Phil Davis
	} else {
1207 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_search";
1208 1e0b1727 Phil Davis
	}
1209 55eb9c44 --global
1210 7a938f1b Ermal
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1211
	$info = @ldap_get_entries($ldap, $search);
1212 55eb9c44 --global
1213
	if (is_array($info)) {
1214
		foreach ($info as $inf) {
1215
			if (!$show_complete_ou) {
1216 cfbfd941 smos
				$inf_split = explode(",", $inf['dn']);
1217 55eb9c44 --global
				$ou = $inf_split[0];
1218 4de8f7ba Phil Davis
				$ou = str_replace("OU=", "", $ou);
1219
				$ou = str_replace("CN=", "", $ou);
1220 1e0b1727 Phil Davis
			} else {
1221
				if ($inf['dn']) {
1222 55eb9c44 --global
					$ou = $inf['dn'];
1223 1e0b1727 Phil Davis
				}
1224
			}
1225
			if ($ou) {
1226 55eb9c44 --global
				$ous[] = $ou;
1227 1e0b1727 Phil Davis
			}
1228 55eb9c44 --global
		}
1229
	}
1230
1231 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1232
1233 55eb9c44 --global
	return $ous;
1234
}
1235
1236 6306b5dd Ermal Lu?i
function ldap_get_groups($username, $authcfg) {
1237 55eb9c44 --global
	global $debug, $config;
1238 1180e4f0 Sjon Hortensius
1239 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1240 55eb9c44 --global
		return;
1241 1e0b1727 Phil Davis
	}
1242 1180e4f0 Sjon Hortensius
1243 1e0b1727 Phil Davis
	if (!$username) {
1244 55eb9c44 --global
		return false;
1245 1e0b1727 Phil Davis
	}
1246 55eb9c44 --global
1247 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1248 2ce660ad smos
		$username_split = explode("@", $username);
1249 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1250 55eb9c44 --global
	}
1251
1252 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1253 cfbfd941 smos
		$username_split = explode("\\", $username);
1254 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1255
	}
1256
1257 55eb9c44 --global
	//log_error("Getting LDAP groups for {$username}.");
1258 1e0b1727 Phil Davis
	if ($authcfg) {
1259 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1260 1e0b1727 Phil Davis
			$ldapproto = "ldaps";
1261 d672403c derelict-pf
		} else {
1262
			$ldapproto = "ldap";
1263 1e0b1727 Phil Davis
		}
1264
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1265
		$ldapport = $authcfg['ldap_port'];
1266
		if (!empty($ldapport)) {
1267 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1268 1e0b1727 Phil Davis
		}
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 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1286 1e0b1727 Phil Davis
	} else {
1287 6306b5dd Ermal Lu?i
		return false;
1288 1e0b1727 Phil Davis
	}
1289 c61e4626 Ermal Lu?i
1290 149efbea jim-p
	if (isset($authcfg['ldap_rfc2307'])) {
1291
		$ldapdn = $ldapbasedn;
1292
	} else {
1293
		$ldapdn = $_SESSION['ldapdn'];
1294
	}
1295 c61e4626 Ermal Lu?i
1296 55eb9c44 --global
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1297
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1298 c61e4626 Ermal Lu?i
	$memberof = array();
1299 55eb9c44 --global
1300
	/* connect and see if server is up */
1301 c61e4626 Ermal Lu?i
	$error = false;
1302 1e0b1727 Phil Davis
	if (!($ldap = ldap_connect($ldapserver))) {
1303 9f27de6d jim-p
		$error = true;
1304 1e0b1727 Phil Davis
	}
1305 c61e4626 Ermal Lu?i
1306
	if ($error == true) {
1307 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1308 0241b34f Phil Davis
		return $memberof;
1309 1e0b1727 Phil Davis
	}
1310 1180e4f0 Sjon Hortensius
1311 b0c7d642 jim-p
	/* Setup CA environment if needed. */
1312
	ldap_setup_caenv($ldap, $authcfg);
1313
1314 55eb9c44 --global
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1315 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1316 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1317 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1318
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1319 55eb9c44 --global
1320 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1321 ff500c90 jim-p
		if (!(@ldap_start_tls($ldap))) {
1322 d672403c derelict-pf
			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 55eb9c44 --global
	/* bind as user that has rights to read group attributes */
1329 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1330
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1331 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1332 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1333 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1334 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1335 1e0b1727 Phil Davis
			return false;
1336 6306b5dd Ermal Lu?i
		}
1337 c61e4626 Ermal Lu?i
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1338 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1339 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1340 0241b34f Phil Davis
		return $memberof;
1341 55eb9c44 --global
	}
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 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1348
		$ldapfunc = "ldap_list";
1349
	} else {
1350
		$ldapfunc = "ldap_search";
1351
	}
1352 c61e4626 Ermal Lu?i
1353 3f6151d7 Viktor G
	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 5cbea686 jim-p
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1376 1e0b1727 Phil Davis
	$info = @ldap_get_entries($ldap, $search);
1377 55eb9c44 --global
1378 149efbea jim-p
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1379 1180e4f0 Sjon Hortensius
1380 4e322e2c Phil Davis
	if (is_array($gresults)) {
1381 55eb9c44 --global
		/* Iterate through the groups and throw them into an array */
1382 149efbea jim-p
		foreach ($gresults as $grp) {
1383 4e322e2c Phil Davis
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1384
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1385 149efbea jim-p
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1386
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1387 55eb9c44 --global
			}
1388
		}
1389
	}
1390 1180e4f0 Sjon Hortensius
1391 55eb9c44 --global
	/* Time to close LDAP connection */
1392 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1393 1180e4f0 Sjon Hortensius
1394 4de8f7ba Phil Davis
	$groups = print_r($memberof, true);
1395 1180e4f0 Sjon Hortensius
1396 55eb9c44 --global
	//log_error("Returning groups ".$groups." for user $username");
1397 1180e4f0 Sjon Hortensius
1398 55eb9c44 --global
	return $memberof;
1399
}
1400
1401 83e0d4c8 jim-p
function ldap_format_host($host) {
1402
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1403
}
1404
1405 eb43c5b1 Augustin FL
function ldap_backed($username, $passwd, $authcfg, &$attributes = array()) {
1406 55eb9c44 --global
	global $debug, $config;
1407 1180e4f0 Sjon Hortensius
1408 1e0b1727 Phil Davis
	if (!$username) {
1409 eb43c5b1 Augustin FL
		$attributes['error_message'] = gettext("Invalid Login.");
1410
		return false;
1411 1e0b1727 Phil Davis
	}
1412 55eb9c44 --global
1413 eeceb2ca Augustin-FL
	if (!isset($authcfg['ldap_allow_unauthenticated']) && $passwd == '') {
1414
		$attributes['error_message'] = gettext("Invalid credentials.");
1415
		return false;
1416
	}
1417
1418 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1419 eb43c5b1 Augustin FL
		log_error(gettext("ERROR! unable to find ldap_connect() function."));
1420
		$attributes['error_message'] = gettext("Internal error during authentication.");
1421
		return null;
1422 1e0b1727 Phil Davis
	}
1423 55eb9c44 --global
1424 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1425 2ce660ad smos
		$username_split = explode("@", $username);
1426 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1427 55eb9c44 --global
	}
1428 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1429 cfbfd941 smos
		$username_split = explode("\\", $username);
1430 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1431 55eb9c44 --global
	}
1432
1433 f0b0a03b jim-p
	$username = ldap_escape($username, null, LDAP_ESCAPE_FILTER);
1434
1435 c61e4626 Ermal Lu?i
	if ($authcfg) {
1436 d672403c derelict-pf
		if (strstr($authcfg['ldap_urltype'], "SSL")) {
1437 c61e4626 Ermal Lu?i
			$ldapproto = "ldaps";
1438 d672403c derelict-pf
		} else {
1439
			$ldapproto = "ldap";
1440 1e0b1727 Phil Davis
		}
1441
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1442
		$ldapport = $authcfg['ldap_port'];
1443
		if (!empty($ldapport)) {
1444 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1445 1e0b1727 Phil Davis
		}
1446
		$ldapbasedn = $authcfg['ldap_basedn'];
1447
		$ldapbindun = $authcfg['ldap_binddn'];
1448
		$ldapbindpw = $authcfg['ldap_bindpw'];
1449
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1450 c61e4626 Ermal Lu?i
			$ldapanon = true;
1451 1e0b1727 Phil Davis
		} else {
1452 c61e4626 Ermal Lu?i
			$ldapanon = false;
1453 1e0b1727 Phil Davis
		}
1454
		$ldapauthcont = $authcfg['ldap_authcn'];
1455
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1456 0a9163aa Steve Powers
		$ldapgroupattribute = $authcfg['ldap_attr_member'];
1457 1e0b1727 Phil Davis
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1458
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1459
		$ldapfilter = "";
1460
		if (!$ldapextendedqueryenabled) {
1461
			$ldapfilter = "({$ldapnameattribute}={$username})";
1462
		} else {
1463 0a9163aa Steve Powers
			if (isset($authcfg['ldap_rfc2307'])) {
1464
				$ldapfilter = "({$ldapnameattribute}={$username})";
1465
				$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1466
			} else {
1467
				$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1468
			}
1469 1e0b1727 Phil Davis
		}
1470
		$ldaptype = "";
1471
		$ldapver = $authcfg['ldap_protver'];
1472
		$ldapname = $authcfg['name'];
1473
		$ldapscope = $authcfg['ldap_scope'];
1474 e8c09a23 Chris Buechler
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 5;
1475 1e0b1727 Phil Davis
	} else {
1476 eb43c5b1 Augustin FL
		return null;
1477 1e0b1727 Phil Davis
	}
1478 55eb9c44 --global
1479 1180e4f0 Sjon Hortensius
	/* first check if there is even an LDAP server populated */
1480 1e0b1727 Phil Davis
	if (!$ldapserver) {
1481 eb43c5b1 Augustin FL
		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 55eb9c44 --global
	}
1485 1180e4f0 Sjon Hortensius
1486 d672403c derelict-pf
	/* Make sure we can connect to LDAP */
1487
	$error = false;
1488
	if (!($ldap = ldap_connect($ldapserver))) {
1489
		$error = true;
1490
	}
1491
1492 b0c7d642 jim-p
	/* Setup CA environment if needed. */
1493
	ldap_setup_caenv($ldap, $authcfg);
1494
1495 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1496 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1497 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1498 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1499
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1500 906daddc Ermal
1501 d672403c derelict-pf
	if (strstr($authcfg['ldap_urltype'], "STARTTLS")) {
1502 b2c7a79c jim-p
		if (!(@ldap_start_tls($ldap))) {
1503 eb43c5b1 Augustin FL
			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 d672403c derelict-pf
			@ldap_close($ldap);
1506 eb43c5b1 Augustin FL
			return null;
1507 d672403c derelict-pf
		}
1508 1e0b1727 Phil Davis
	}
1509 c61e4626 Ermal Lu?i
1510
	if ($error == true) {
1511 eb43c5b1 Augustin FL
		$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 55eb9c44 --global
	}
1515 c61e4626 Ermal Lu?i
1516 55eb9c44 --global
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1517 c61e4626 Ermal Lu?i
	$error = false;
1518 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1519
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1520 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1521 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1522
			$error = true;
1523
		}
1524
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1525 c61e4626 Ermal Lu?i
		$error = true;
1526 1e0b1727 Phil Davis
	}
1527 c61e4626 Ermal Lu?i
1528
	if ($error == true) {
1529 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1530 eb43c5b1 Augustin FL
		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 55eb9c44 --global
	}
1534 1180e4f0 Sjon Hortensius
1535 55eb9c44 --global
	/* Get LDAP Authcontainers and split em up. */
1536 cfbfd941 smos
	$ldac_splits = explode(";", $ldapauthcont);
1537 1180e4f0 Sjon Hortensius
1538 086cf944 Phil Davis
	/* setup the usercount so we think we haven't found anyone yet */
1539 4de8f7ba Phil Davis
	$usercount = 0;
1540 55eb9c44 --global
1541
	/*****************************************************************/
1542 6990ad35 Phil Davis
	/*  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 55eb9c44 --global
	/*  that way we don't have to search twice.                      */
1547
	/*****************************************************************/
1548 1e0b1727 Phil Davis
	if ($debug) {
1549 3ac8324f Ermal
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1550 1e0b1727 Phil Davis
	}
1551 c61e4626 Ermal Lu?i
	/* Iterate through the user containers for search */
1552
	foreach ($ldac_splits as $i => $ldac_split) {
1553 a5cd1c5a jim-p
		$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 c61e4626 Ermal Lu?i
		/* Make sure we just use the first user we find */
1557 1e0b1727 Phil Davis
		if ($debug) {
1558 a5cd1c5a jim-p
			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 1e0b1727 Phil Davis
		}
1560
		if ($ldapscope == "one") {
1561 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_list";
1562 1e0b1727 Phil Davis
		} else {
1563 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_search";
1564 1e0b1727 Phil Davis
		}
1565 c61e4626 Ermal Lu?i
		/* Support legacy auth container specification. */
1566 1e0b1727 Phil Davis
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1567 3f6151d7 Viktor G
			$ldapdn = $ldac_split;
1568 1e0b1727 Phil Davis
		} else {
1569 3f6151d7 Viktor G
			$ldapdn = $ldapsearchbasedn;
1570
		}
1571
		$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter);
1572 ac4a56f1 Viktor G
		if (!$search) {
1573
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1574
			continue;
1575
		}
1576 3f6151d7 Viktor G
		if (isset($authcfg['ldap_rfc2307']) && isset($ldapgroupfilter)) {
1577
			if (isset($authcfg['ldap_rfc2307_userdn'])) {
1578 ac4a56f1 Viktor G
				$info = ldap_get_entries($ldap, $search);
1579 3f6151d7 Viktor G
				$username = $info[0]['dn'];
1580 0a9163aa Steve Powers
			}
1581 3f6151d7 Viktor G
			$ldapgroupfilter = "(&({$ldapgroupattribute}={$username})({$ldapextendedquery}))";
1582 ac4a56f1 Viktor G
			$groupsearch = @$ldapfunc($ldap, $ldapdn, $ldapgroupfilter);
1583 0a9163aa Steve Powers
		}
1584
1585
		if (isset($ldapgroupfilter) && !$groupsearch) {
1586
			log_error(sprintf(gettext("Extended group search resulted in error: %s"), ldap_error($ldap)));
1587
			continue;
1588 1e0b1727 Phil Davis
		}
1589 0a9163aa Steve Powers
		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 5cbea686 jim-p
		$info = ldap_get_entries($ldap, $search);
1596 c61e4626 Ermal Lu?i
		$matches = $info['count'];
1597 1e0b1727 Phil Davis
		if ($matches == 1) {
1598 c61e4626 Ermal Lu?i
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1599
			$_SESSION['ldapou'] = $ldac_split[$i];
1600
			$_SESSION['ldapon'] = "true";
1601
			$usercount = 1;
1602
			break;
1603 55eb9c44 --global
		}
1604
	}
1605
1606 1e0b1727 Phil Davis
	if ($usercount != 1) {
1607 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1608 eb43c5b1 Augustin FL
		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 1180e4f0 Sjon Hortensius
		return false;
1617 55eb9c44 --global
	}
1618 c61e4626 Ermal Lu?i
1619 55eb9c44 --global
	/* Now lets bind as the user we found */
1620 a5cd1c5a jim-p
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1621 c61e4626 Ermal Lu?i
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1622 eb43c5b1 Augustin FL
		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 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1626 c61e4626 Ermal Lu?i
		return false;
1627 55eb9c44 --global
	}
1628
1629 a5cd1c5a jim-p
	if ($debug) {
1630
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1631 2004def5 Ermal
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1632 a5cd1c5a jim-p
	}
1633 c61e4626 Ermal Lu?i
1634 0a9163aa Steve Powers
	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 c61e4626 Ermal Lu?i
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1639 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1640 55eb9c44 --global
1641 0a9163aa Steve Powers
	if (isset($ldapgroupfilter) && $validgroup < 1) {
1642
		return false;
1643
	}
1644
1645 55eb9c44 --global
	return true;
1646
}
1647
1648 9da4a575 Renato Botelho
function radius_backed($username, $password, $authcfg, &$attributes = array()) {
1649 a13ce628 Ermal Lu?i
	global $debug, $config;
1650 55eb9c44 --global
	$ret = false;
1651
1652 49ec9d91 Renato Botelho
	require_once("Auth/RADIUS.php");
1653 9da4a575 Renato Botelho
	require_once("Crypt/CHAP.php");
1654 868c6826 Ermal
1655 c61e4626 Ermal Lu?i
	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 bddd2be8 jim-p
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1661 9da4a575 Renato Botelho
		if(isset($authcfg['radius_protocol'])) {
1662
			$radius_protocol = $authcfg['radius_protocol'];
1663
		} else {
1664
			$radius_protocol = 'PAP';
1665
		}
1666 1e0b1727 Phil Davis
	} else {
1667 f15fdef3 Augustin FL
		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 1e0b1727 Phil Davis
	}
1671 c61e4626 Ermal Lu?i
1672 9da4a575 Renato Botelho
	// Create our instance
1673
	$classname = 'Auth_RADIUS_' . $radius_protocol;
1674
	$rauth = new $classname($username, $password);
1675
1676 1e0b1727 Phil Davis
	/* Add new servers to our instance */
1677 bddd2be8 jim-p
	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 55eb9c44 --global
1682 9da4a575 Renato Botelho
	// 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 6e815096 Ermal
	if (PEAR::isError($rauth->start())) {
1713 f15fdef3 Augustin FL
		$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 f3f98e97 Phil Davis
1725 f15fdef3 Augustin FL
			if (!is_ipaddr($nasip)) {
1726 5bd66059 Viktor G
				/* 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 f15fdef3 Augustin FL
			}
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 f3f98e97 Phil Davis
1741 f15fdef3 Augustin FL
		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 f3f98e97 Phil Davis
		}
1752 f15fdef3 Augustin FL
		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 1e0b1727 Phil Davis
		}
1758 55eb9c44 --global
	}
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 f15fdef3 Augustin FL
		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 55eb9c44 --global
	} else if ($result === true) {
1769
		$ret = true;
1770
	} else {
1771 f15fdef3 Augustin FL
		$ret = false;
1772 55eb9c44 --global
	}
1773
1774 f3f98e97 Phil Davis
1775 f15fdef3 Augustin FL
	// 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 f3f98e97 Phil Davis
1786 f15fdef3 Augustin FL
	// close OO RADIUS_AUTHENTICATION
1787 55eb9c44 --global
	$rauth->close();
1788
1789
	return $ret;
1790
}
1791
1792 c4a9f99a jim-p
/*
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 461bae6b jim-p
	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 c4a9f99a jim-p
		foreach ($groups as & $grp) {
1808 916fc1f8 jim-p
			$grp = trim($grp);
1809
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1810 c4a9f99a jim-p
				$grp = substr($grp, 3);
1811
			}
1812
		}
1813
	}
1814
	return $groups;
1815
}
1816
1817 7dd044f2 sullrich
function get_user_expiration_date($username) {
1818 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1819 1e0b1727 Phil Davis
	if ($user['expires']) {
1820 a13ce628 Ermal Lu?i
		return $user['expires'];
1821 1e0b1727 Phil Davis
	}
1822 a13ce628 Ermal Lu?i
}
1823
1824
function is_account_expired($username) {
1825
	$expirydate = get_user_expiration_date($username);
1826
	if ($expirydate) {
1827 4de8f7ba Phil Davis
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1828 a13ce628 Ermal Lu?i
			return true;
1829 1e0b1727 Phil Davis
		}
1830 7dd044f2 sullrich
	}
1831 a13ce628 Ermal Lu?i
1832
	return false;
1833 7dd044f2 sullrich
}
1834
1835 b4bfd25d sullrich
function is_account_disabled($username) {
1836 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1837 1e0b1727 Phil Davis
	if (isset($user['disabled'])) {
1838 a13ce628 Ermal Lu?i
		return true;
1839 1e0b1727 Phil Davis
	}
1840 a13ce628 Ermal Lu?i
1841 b4bfd25d sullrich
	return false;
1842
}
1843
1844 8bab524e Phil Davis
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 e79ff1ee Steve Beaver
	$settings['webgui']['logincss'] = $config['system']['webgui']['logincss'];
1852 1d3510cf Phil Davis
	$settings['webgui']['interfacessort'] = isset($config['system']['webgui']['interfacessort']);
1853 8bab524e Phil Davis
	$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 d9058974 Phil Davis
	$settings['webgui']['disablealiaspopupdetail'] = isset($config['system']['webgui']['disablealiaspopupdetail']);
1857 8bab524e Phil Davis
	$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 1d3510cf Phil Davis
		$settings['webgui']['interfacessort'] = isset($user['interfacessort']);
1878 8bab524e Phil Davis
		$settings['webgui']['dashboardavailablewidgetspanel'] = isset($user['dashboardavailablewidgetspanel']);
1879
		$settings['webgui']['webguifixedmenu'] = isset($user['webguifixedmenu']);
1880
		$settings['webgui']['webguileftcolumnhyper'] = isset($user['webguileftcolumnhyper']);
1881 d9058974 Phil Davis
		$settings['webgui']['disablealiaspopupdetail'] = isset($user['disablealiaspopupdetail']);
1882 8bab524e Phil Davis
		$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 2b7d0520 Phil Davis
function save_widget_settings($username, $settings, $message = "") {
1898 8bab524e Phil Davis
	global $config, $userindex;
1899
	$user = getUserEntry($username);
1900 2b7d0520 Phil Davis
1901
	if (strlen($message) > 0) {
1902
		$msgout = $message;
1903
	} else {
1904
		$msgout = gettext("Widget configuration has been changed.");
1905
	}
1906
1907 8bab524e Phil Davis
	if (isset($user['customsettings'])) {
1908
		$config['system']['user'][$userindex[$username]]['widgets'] = $settings;
1909 2b7d0520 Phil Davis
		write_config($msgout . " " . sprintf(gettext("(User %s)"), $username));
1910 8bab524e Phil Davis
	} else {
1911
		$config['widgets'] = $settings;
1912 2b7d0520 Phil Davis
		write_config($msgout);
1913 8bab524e Phil Davis
	}
1914
}
1915
1916 c61e4626 Ermal Lu?i
function auth_get_authserver($name) {
1917 1e0b1727 Phil Davis
	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 296c16bd Renato Botelho
		return array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1928 1e0b1727 Phil Davis
	}
1929 6306b5dd Ermal Lu?i
}
1930
1931
function auth_get_authserver_list() {
1932 1e0b1727 Phil Davis
	global $config;
1933 6306b5dd Ermal Lu?i
1934
	$list = array();
1935
1936 1e0b1727 Phil Davis
	if (is_array($config['system']['authserver'])) {
1937
		foreach ($config['system']['authserver'] as $authcfg) {
1938 6306b5dd Ermal Lu?i
			/* Add support for disabled entries? */
1939
			$list[$authcfg['name']] = $authcfg;
1940 1e0b1727 Phil Davis
		}
1941
	}
1942 6306b5dd Ermal Lu?i
1943 296c16bd Renato Botelho
	$list["Local Database"] = array("name" => "Local Database", "type" => "Local Auth", "host" => $config['system']['hostname']);
1944 6306b5dd Ermal Lu?i
	return $list;
1945 c61e4626 Ermal Lu?i
}
1946
1947 c4a9f99a jim-p
function getUserGroups($username, $authcfg, &$attributes = array()) {
1948 fb0f22c0 Ermal Lu?i
	global $config;
1949
1950
	$allowed_groups = array();
1951
1952 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1953
		case 'ldap':
1954
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1955
			break;
1956
		case 'radius':
1957 c4a9f99a jim-p
			$allowed_groups = @radius_get_groups($attributes);
1958 1e0b1727 Phil Davis
			break;
1959
		default:
1960
			$user = getUserEntry($username);
1961
			$allowed_groups = @local_user_get_groups($user, true);
1962
			break;
1963 fb0f22c0 Ermal Lu?i
	}
1964
1965
	$member_groups = array();
1966 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
1967
		foreach ($config['system']['group'] as $group) {
1968
			if (in_array($group['name'], $allowed_groups)) {
1969 fb0f22c0 Ermal Lu?i
				$member_groups[] = $group['name'];
1970 1e0b1727 Phil Davis
			}
1971
		}
1972 fb0f22c0 Ermal Lu?i
	}
1973
1974
	return $member_groups;
1975
}
1976
1977 eb43c5b1 Augustin FL
/*
1978 f3f98e97 Phil Davis
Possible return values :
1979 eb43c5b1 Augustin FL
true : authentication worked
1980 f3f98e97 Phil Davis
false : authentication failed (invalid login/password, not enough permission, etc...)
1981 eb43c5b1 Augustin FL
null : error during authentication process (unable to reach remote server, etc...)
1982
*/
1983 1492e02c Ermal
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1984 c61e4626 Ermal Lu?i
1985 b7369ff8 NewEraCracker
	if (is_array($username) || is_array($password)) {
1986
		return false;
1987
	}
1988
1989 c61e4626 Ermal Lu?i
	if (!$authcfg) {
1990 eb43c5b1 Augustin FL
		return local_backed($username, $password, $attributes);
1991 c61e4626 Ermal Lu?i
	}
1992
1993
	$authenticated = false;
1994 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1995
		case 'ldap':
1996 d832b6ce jim-p
			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 1e0b1727 Phil Davis
			break;
2004
		case 'radius':
2005 d832b6ce jim-p
			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 1e0b1727 Phil Davis
			break;
2011
		default:
2012
			/* lookup user object by name */
2013 d832b6ce jim-p
			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 1e0b1727 Phil Davis
			break;
2019
		}
2020 c61e4626 Ermal Lu?i
2021
	return $authenticated;
2022
}
2023
2024 6306b5dd Ermal Lu?i
function session_auth() {
2025 aa205c3b Ermal
	global $config, $_SESSION, $page;
2026 55eb9c44 --global
2027 49ddf9a1 Warren Baker
	// Handle HTTPS httponly and secure flags
2028 16789caa Renato Botelho
	$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 49ddf9a1 Warren Baker
2037 82cd6022 PiBa-NL
	phpsession_begin();
2038 55eb9c44 --global
2039 dd030de9 Renato Botelho
	// Detect protocol change
2040 1e0b1727 Phil Davis
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
2041 82cd6022 PiBa-NL
		phpsession_end();
2042 dd030de9 Renato Botelho
		return false;
2043 1e0b1727 Phil Davis
	}
2044 dd030de9 Renato Botelho
2045 55eb9c44 --global
	/* Validate incoming login request */
2046 5ad5ead1 Shawn Bruce
	$attributes = array('nas_identifier' => 'webConfigurator-' . gethostname());
2047 eeceb2ca Augustin-FL
	if (isset($_POST['login']) && !empty($_POST['usernamefld'])) {
2048 6306b5dd Ermal Lu?i
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
2049 b77a6394 PiBa-NL
		$remoteauth = authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes);
2050
		if ($remoteauth || authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
2051 526f5b11 Renato Botelho
			// Generate a new id to avoid session fixation
2052 8588095f Renato Botelho
			session_regenerate_id();
2053 6306b5dd Ermal Lu?i
			$_SESSION['Logged_In'] = "True";
2054 b77a6394 PiBa-NL
			$_SESSION['remoteauth'] = $remoteauth;
2055 d629601a jim-p
			if ($remoteauth) {
2056 80dbe344 jim-p
				if (empty($authcfg['type']) || ($authcfg['type'] == "Local Auth")) {
2057 296c16bd Renato Botelho
					$_SESSION['authsource'] = "Local Database";
2058 80dbe344 jim-p
				} else {
2059 296c16bd Renato Botelho
					$_SESSION['authsource'] = strtoupper($authcfg['type']) . "/{$authcfg['name']}";
2060 80dbe344 jim-p
				}
2061 d629601a jim-p
			} else {
2062 296c16bd Renato Botelho
				$_SESSION['authsource'] = 'Local Database Fallback';
2063 d629601a jim-p
			}
2064 6306b5dd Ermal Lu?i
			$_SESSION['Username'] = $_POST['usernamefld'];
2065 c4a9f99a jim-p
			$_SESSION['user_radius_attributes'] = $attributes;
2066 6306b5dd Ermal Lu?i
			$_SESSION['last_access'] = time();
2067 dd030de9 Renato Botelho
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
2068 82cd6022 PiBa-NL
			phpsession_end(true);
2069 1e0b1727 Phil Davis
			if (!isset($config['system']['webgui']['quietlogin'])) {
2070 d629601a jim-p
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], get_user_remote_address() . get_user_remote_authsource()));
2071 4fc3855f smos
			}
2072 1e0b1727 Phil Davis
			if (isset($_POST['postafterlogin'])) {
2073 92140621 Ermal
				return true;
2074 1e0b1727 Phil Davis
			} else {
2075
				if (empty($page)) {
2076 80b292f3 Ermal
					$page = "/";
2077 1e0b1727 Phil Davis
				}
2078 80b292f3 Ermal
				header("Location: {$page}");
2079
			}
2080 f23e6363 Ermal
			exit;
2081 a13ce628 Ermal Lu?i
		} else {
2082
			/* give the user an error message */
2083 ca44a37c Steve Beaver
			$_SESSION['Login_Error'] = gettext("Username or Password incorrect");
2084 d629601a jim-p
			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 1e0b1727 Phil Davis
			if (isAjax()) {
2086 a13ce628 Ermal Lu?i
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
2087
				return;
2088 55eb9c44 --global
			}
2089
		}
2090
	}
2091
2092
	/* Show login page if they aren't logged in */
2093 1e0b1727 Phil Davis
	if (empty($_SESSION['Logged_In'])) {
2094 82cd6022 PiBa-NL
		phpsession_end(true);
2095 55eb9c44 --global
		return false;
2096 1e0b1727 Phil Davis
	}
2097 55eb9c44 --global
2098
	/* If session timeout isn't set, we don't mark sessions stale */
2099 02647583 Ermal
	if (!isset($config['system']['webgui']['session_timeout'])) {
2100 bdadaf3c Chris Buechler
		/* Default to 4 hour timeout if one is not set */
2101
		if ($_SESSION['last_access'] < (time() - 14400)) {
2102 ce437697 Steve Beaver
			$_POST['logout'] = true;
2103 bdadaf3c Chris Buechler
			$_SESSION['Logout'] = true;
2104 1e0b1727 Phil Davis
		} else {
2105 1180e4f0 Sjon Hortensius
			$_SESSION['last_access'] = time();
2106 1e0b1727 Phil Davis
		}
2107 02647583 Ermal
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
2108
		/* only update if it wasn't ajax */
2109 1e0b1727 Phil Davis
		if (!isAjax()) {
2110 02647583 Ermal
			$_SESSION['last_access'] = time();
2111 1e0b1727 Phil Davis
		}
2112 bdadaf3c Chris Buechler
	} else {
2113 55eb9c44 --global
		/* Check for stale session */
2114
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
2115 ce437697 Steve Beaver
			$_POST['logout'] = true;
2116 55eb9c44 --global
			$_SESSION['Logout'] = true;
2117
		} else {
2118
			/* only update if it wasn't ajax */
2119 1e0b1727 Phil Davis
			if (!isAjax()) {
2120 55eb9c44 --global
				$_SESSION['last_access'] = time();
2121 1e0b1727 Phil Davis
			}
2122 55eb9c44 --global
		}
2123
	}
2124
2125
	/* user hit the logout button */
2126 ce437697 Steve Beaver
	if (isset($_POST['logout'])) {
2127 55eb9c44 --global
2128 1e0b1727 Phil Davis
		if ($_SESSION['Logout']) {
2129 d629601a jim-p
			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 1e0b1727 Phil Davis
		} else {
2131 d629601a jim-p
			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 1e0b1727 Phil Davis
		}
2133 55eb9c44 --global
2134
		/* wipe out $_SESSION */
2135
		$_SESSION = array();
2136
2137 1e0b1727 Phil Davis
		if (isset($_COOKIE[session_name()])) {
2138 55eb9c44 --global
			setcookie(session_name(), '', time()-42000, '/');
2139 1e0b1727 Phil Davis
		}
2140 55eb9c44 --global
2141
		/* and destroy it */
2142 82cd6022 PiBa-NL
		phpsession_destroy();
2143 55eb9c44 --global
2144 cfbfd941 smos
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
2145 55eb9c44 --global
		$scriptElms = count($scriptName);
2146
		$scriptName = $scriptName[$scriptElms-1];
2147
2148 1e0b1727 Phil Davis
		if (isAjax()) {
2149 55eb9c44 --global
			return false;
2150 1e0b1727 Phil Davis
		}
2151 55eb9c44 --global
2152
		/* redirect to page the user is on, it'll prompt them to login again */
2153 6f3d2063 Renato Botelho
		header("Location: {$scriptName}");
2154 55eb9c44 --global
2155
		return false;
2156
	}
2157
2158
	/*
2159
	 * this is for debugging purpose if you do not want to use Ajax
2160 1e0b1727 Phil Davis
	 * to submit a HTML form. It basically disables the observation
2161 55eb9c44 --global
	 * of the submit event and hence does not trigger Ajax.
2162
	 */
2163 8d58ebae Steve Beaver
	if ($_REQUEST['disable_ajax']) {
2164 55eb9c44 --global
		$_SESSION['NO_AJAX'] = "True";
2165 1e0b1727 Phil Davis
	}
2166 55eb9c44 --global
2167
	/*
2168
	 * Same to re-enable Ajax.
2169
	 */
2170 8d58ebae Steve Beaver
	if ($_REQUEST['enable_ajax']) {
2171 55eb9c44 --global
		unset($_SESSION['NO_AJAX']);
2172 1e0b1727 Phil Davis
	}
2173 82cd6022 PiBa-NL
	phpsession_end(true);
2174 55eb9c44 --global
	return true;
2175
}
2176
2177 16050763 Steve Beaver
function print_credit() {
2178
	global $g;
2179
2180 573ec19d Renato Botelho do Couto
	return  '<a target="_blank" href="https://pfsense.org">' . $g["product_label"] . '</a>' .
2181 16050763 Steve Beaver
			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 d629601a jim-p
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 4594c689 Viktor G
2203
function set_pam_auth() {
2204
	global $config;
2205
2206 ca8459cd Viktor G
	$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 4594c689 Viktor G
	$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 ca8459cd Viktor G
	$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 4594c689 Viktor G
# 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 ca8459cd Viktor G
			$pam_system =<<<EOD
2288 4594c689 Viktor G
# 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 ca8459cd Viktor G
			@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 d0f746e3 jim-p
			@unlink_if_exists("/usr/local/etc/nss_ldap.conf");
2403 ca8459cd Viktor G
			@symlink("/var/etc/pam_ldap.conf", "/usr/local/etc/nss_ldap.conf");
2404
		}
2405 4594c689 Viktor G
	}
2406
2407
	@file_put_contents("/etc/pam.d/sshd", $header . $pam_sshd);
2408
	@file_put_contents("/etc/pam.d/system", $header . $pam_system);
2409 ca8459cd Viktor G
	@file_put_contents("/etc/nsswitch.conf", $header . $nsswitch);
2410 4594c689 Viktor G
}
2411 88165371 Ermal
?>