Project

General

Profile

Download (46.8 KB) Statistics
| Branch: | Tag: | Revision:
1 55eb9c44 --global
<?php
2 b37b4034 Phil Davis
/*
3
	auth.inc
4
*/
5 995df6c3 Stephen Beaver
/* ====================================================================
6
 *	Copyright (c)  2004-2015  Electric Sheep Fencing, LLC. All rights reserved.
7 cb41dd63 Renato Botelho
 *	Copyright (c)  2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
 *	Copyright (c)  2006 Paul Taylor <paultaylor@winn-dixie.com>
9 b37b4034 Phil Davis
 *	Copyright (c)  2003-2006 Manuel Kasper <mk@neon1.net>
10 995df6c3 Stephen Beaver
 *
11
 *	Redistribution and use in source and binary forms, with or without modification,
12
 *	are permitted provided that the following conditions are met:
13
 *
14
 *	1. Redistributions of source code must retain the above copyright notice,
15
 *		this list of conditions and the following disclaimer.
16
 *
17
 *	2. Redistributions in binary form must reproduce the above copyright
18
 *		notice, this list of conditions and the following disclaimer in
19
 *		the documentation and/or other materials provided with the
20
 *		distribution.
21
 *
22
 *	3. All advertising materials mentioning features or use of this software
23
 *		must display the following acknowledgment:
24
 *		"This product includes software developed by the pfSense Project
25
 *		 for use in the pfSense software distribution. (http://www.pfsense.org/).
26
 *
27
 *	4. The names "pfSense" and "pfSense Project" must not be used to
28
 *		 endorse or promote products derived from this software without
29
 *		 prior written permission. For written permission, please contact
30
 *		 coreteam@pfsense.org.
31
 *
32
 *	5. Products derived from this software may not be called "pfSense"
33
 *		nor may "pfSense" appear in their names without prior written
34
 *		permission of the Electric Sheep Fencing, LLC.
35
 *
36
 *	6. Redistributions of any form whatsoever must retain the following
37
 *		acknowledgment:
38
 *
39
 *	"This product includes software developed by the pfSense Project
40
 *	for use in the pfSense software distribution (http://www.pfsense.org/).
41
 *
42
 *	THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
43
 *	EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44
 *	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
45
 *	PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
46
 *	ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47
 *	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
48
 *	NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
49
 *	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50
 *	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51
 *	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52
 *	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53
 *	OF THE POSSIBILITY OF SUCH DAMAGE.
54
 *
55
 *	====================================================================
56
 *
57
 */
58 55eb9c44 --global
/*
59
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
60
 * file courtesy of Michael Retterklieber.
61
 */
62 1e0b1727 Phil Davis
if (!$do_not_include_config_gui_inc) {
63 052e65ef Scott Ullrich
	require_once("config.gui.inc");
64 1e0b1727 Phil Davis
}
65 55eb9c44 --global
66 9ae11a62 Scott Ullrich
// Will be changed to false if security checks fail
67
$security_passed = true;
68
69 1180e4f0 Sjon Hortensius
/* If this function doesn't exist, we're being called from Captive Portal or
70 0321fa1b jim-p
   another internal subsystem which does not include authgui.inc */
71 14eab6fb jim-p
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nodnsrebindcheck'])) {
72 0734024c Chris Buechler
	/* DNS ReBinding attack prevention.  https://redmine.pfsense.org/issues/708 */
73 0321fa1b jim-p
	$found_host = false;
74 209620ea Seth Mos
75 4cf79fdd smos
	/* Either a IPv6 address with or without a alternate port */
76 1e0b1727 Phil Davis
	if (strstr($_SERVER['HTTP_HOST'], "]")) {
77 4cf79fdd smos
		$http_host_port = explode("]", $_SERVER['HTTP_HOST']);
78 209620ea Seth Mos
		/* v6 address has more parts, drop the last part */
79 1e0b1727 Phil Davis
		if (count($http_host_port) > 1) {
80 209620ea Seth Mos
			array_pop($http_host_port);
81
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
82
		} else {
83 4cf79fdd smos
			$http_host = str_replace(array("[", "]"), "", implode(":", $http_host_port));
84 209620ea Seth Mos
		}
85 7319dc73 jim-p
	} else {
86 4fcab77b smos
		$http_host = explode(":", $_SERVER['HTTP_HOST']);
87
		$http_host = $http_host[0];
88 7319dc73 jim-p
	}
89 1e0b1727 Phil Davis
	if (is_ipaddr($http_host) or $_SERVER['SERVER_ADDR'] == "127.0.0.1" or
90 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, "localhost") == 0 or $_SERVER['SERVER_ADDR'] == "::1") {
91 9ae11a62 Scott Ullrich
		$found_host = true;
92 1e0b1727 Phil Davis
	}
93
	if (strcasecmp($http_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 or
94 46bb8a0b Sjon Hortensius
		strcasecmp($http_host, $config['system']['hostname']) == 0) {
95 d7bf3178 Erik Fonnesbeck
		$found_host = true;
96 1e0b1727 Phil Davis
	}
97 9ae11a62 Scott Ullrich
98 1e0b1727 Phil Davis
	if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
99
		foreach ($config['dyndnses']['dyndns'] as $dyndns) {
100
			if (strcasecmp($dyndns['host'], $http_host) == 0) {
101 0321fa1b jim-p
				$found_host = true;
102 9ae11a62 Scott Ullrich
				break;
103
			}
104 1e0b1727 Phil Davis
		}
105
	}
106 7319dc73 jim-p
107 1e0b1727 Phil Davis
	if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
108
		foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
109
			if (strcasecmp($rfc2136['host'], $http_host) == 0) {
110 fa087612 jim-p
				$found_host = true;
111
				break;
112
			}
113 1e0b1727 Phil Davis
		}
114
	}
115 fa087612 jim-p
116 1e0b1727 Phil Davis
	if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
117 86b21903 jim-p
		$althosts = explode(" ", $config['system']['webgui']['althostnames']);
118 1e0b1727 Phil Davis
		foreach ($althosts as $ah) {
119
			if (strcasecmp($ah, $http_host) == 0 or strcasecmp($ah, $_SERVER['SERVER_ADDR']) == 0) {
120 86b21903 jim-p
				$found_host = true;
121 9ae11a62 Scott Ullrich
				break;
122
			}
123 1e0b1727 Phil Davis
		}
124 9b13f84b Scott Ullrich
	}
125 ce46b5da Scott Ullrich
126 1e0b1727 Phil Davis
	if ($found_host == false) {
127
		if (!security_checks_disabled()) {
128 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."));
129 9ae11a62 Scott Ullrich
			exit;
130
		}
131
		$security_passed = false;
132
	}
133
}
134 ef173724 Scott Ullrich
135 9ae11a62 Scott Ullrich
// If the HTTP_REFERER is something other than ourselves then disallow.
136 1e0b1727 Phil Davis
if (function_exists("display_error_form") && !isset($config['system']['webgui']['nohttpreferercheck'])) {
137
	if ($_SERVER['HTTP_REFERER']) {
138
		if (file_exists("{$g['tmp_path']}/setupwizard_lastreferrer")) {
139
			if ($_SERVER['HTTP_REFERER'] == file_get_contents("{$g['tmp_path']}/setupwizard_lastreferrer")) {
140 9ae11a62 Scott Ullrich
				unlink("{$g['tmp_path']}/setupwizard_lastreferrer");
141
				header("Refresh: 1; url=index.php");
142 1180e4f0 Sjon Hortensius
?>
143
<!DOCTYPE html>
144
<html lang="en">
145
<head>
146
	<link rel="stylesheet" href="/bootstrap/css/pfSense.css" />
147
	<title><?=gettext("Redirecting..."); ?></title>
148
</head>
149
<body id="error" class="no-menu">
150
	<div id="jumbotron">
151
		<div class="container">
152 c7d61071 Sander van Leeuwen
			<div class="col-sm-offset-3 col-sm-6 col-xs-12">
153
				<p><?=gettext("Redirecting to the dashboard...")?></p>
154
			</div>
155 1180e4f0 Sjon Hortensius
		</div>
156
	</div>
157
</body>
158
</html>
159
<?php
160 9ae11a62 Scott Ullrich
				exit;
161
			}
162
		}
163
		$found_host = false;
164
		$referrer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
165 e6f7e0be smos
		$referrer_host = str_replace(array("[", "]"), "", $referrer_host);
166 1e0b1727 Phil Davis
		if ($referrer_host) {
167 ae52d165 Renato Botelho
			if (strcasecmp($referrer_host, $config['system']['hostname'] . "." . $config['system']['domain']) == 0 ||
168 4e322e2c Phil Davis
			    strcasecmp($referrer_host, $config['system']['hostname']) == 0) {
169 9ae11a62 Scott Ullrich
				$found_host = true;
170 1e0b1727 Phil Davis
			}
171 9f0bee02 jim-p
172 1e0b1727 Phil Davis
			if (!empty($config['system']['webgui']['althostnames']) && !$found_host) {
173 9ae11a62 Scott Ullrich
				$althosts = explode(" ", $config['system']['webgui']['althostnames']);
174
				foreach ($althosts as $ah) {
175 1e0b1727 Phil Davis
					if (strcasecmp($referrer_host, $ah) == 0) {
176 9ae11a62 Scott Ullrich
						$found_host = true;
177
						break;
178
					}
179
				}
180
			}
181 9f0bee02 jim-p
182 1e0b1727 Phil Davis
			if (is_array($config['dyndnses']['dyndns']) && !$found_host) {
183
				foreach ($config['dyndnses']['dyndns'] as $dyndns) {
184
					if (strcasecmp($dyndns['host'], $referrer_host) == 0) {
185 9f0bee02 jim-p
						$found_host = true;
186
						break;
187
					}
188 1e0b1727 Phil Davis
				}
189
			}
190 9f0bee02 jim-p
191 1e0b1727 Phil Davis
			if (is_array($config['dnsupdates']['dnsupdate']) && !$found_host) {
192
				foreach ($config['dnsupdates']['dnsupdate'] as $rfc2136) {
193
					if (strcasecmp($rfc2136['host'], $referrer_host) == 0) {
194 9f0bee02 jim-p
						$found_host = true;
195
						break;
196
					}
197 1e0b1727 Phil Davis
				}
198
			}
199 9f0bee02 jim-p
200 1e0b1727 Phil Davis
			if (!$found_host) {
201 9ae11a62 Scott Ullrich
				$interface_list_ips = get_configured_ip_addresses();
202 1e0b1727 Phil Davis
				foreach ($interface_list_ips as $ilips) {
203
					if (strcasecmp($referrer_host, $ilips) == 0) {
204 9ae11a62 Scott Ullrich
						$found_host = true;
205
						break;
206
					}
207
				}
208 e6f7e0be smos
				$interface_list_ipv6s = get_configured_ipv6_addresses();
209 1e0b1727 Phil Davis
				foreach ($interface_list_ipv6s as $ilipv6s) {
210
					if (strcasecmp($referrer_host, $ilipv6s) == 0) {
211 e6f7e0be smos
						$found_host = true;
212
						break;
213
					}
214
				}
215 1e0b1727 Phil Davis
				if ($referrer_host == "127.0.0.1" || $referrer_host == "localhost") {
216 17dd7ff3 Chris Buechler
					// allow SSH port forwarded connections and links from localhost
217
					$found_host = true;
218
				}
219 9ae11a62 Scott Ullrich
			}
220
		}
221 1e0b1727 Phil Davis
		if ($found_host == false) {
222
			if (!security_checks_disabled()) {
223 9ae11a62 Scott Ullrich
				display_error_form("501", "An HTTP_REFERER was detected other than what is defined in System -> Advanced (" . htmlspecialchars($_SERVER['HTTP_REFERER']) . ").  You can disable this check if needed in System -> Advanced -> Admin.");
224 0f806eca Erik Fonnesbeck
				exit;
225
			}
226 9ae11a62 Scott Ullrich
			$security_passed = false;
227
		}
228 1e0b1727 Phil Davis
	} else {
229 9ae11a62 Scott Ullrich
		$security_passed = false;
230 1e0b1727 Phil Davis
	}
231 4fe9c2dc Scott Ullrich
}
232
233 1e0b1727 Phil Davis
if (function_exists("display_error_form") && $security_passed) {
234 9ae11a62 Scott Ullrich
	/* Security checks passed, so it should be OK to turn them back on */
235
	restore_security_checks();
236 1e0b1727 Phil Davis
}
237 9ae11a62 Scott Ullrich
unset($security_passed);
238
239 55eb9c44 --global
$groupindex = index_groups();
240
$userindex = index_users();
241
242
function index_groups() {
243
	global $g, $debug, $config, $groupindex;
244
245
	$groupindex = array();
246
247 6dcd80af Ermal
	if (is_array($config['system']['group'])) {
248 55eb9c44 --global
		$i = 0;
249 1e0b1727 Phil Davis
		foreach ($config['system']['group'] as $groupent) {
250 55eb9c44 --global
			$groupindex[$groupent['name']] = $i;
251
			$i++;
252
		}
253
	}
254
255
	return ($groupindex);
256
}
257
258
function index_users() {
259
	global $g, $debug, $config;
260
261 6dcd80af Ermal
	if (is_array($config['system']['user'])) {
262 55eb9c44 --global
		$i = 0;
263 1e0b1727 Phil Davis
		foreach ($config['system']['user'] as $userent) {
264 55eb9c44 --global
			$userindex[$userent['name']] = $i;
265
			$i++;
266
		}
267
	}
268
269
	return ($userindex);
270
}
271
272
function & getUserEntry($name) {
273
	global $debug, $config, $userindex;
274 1e0b1727 Phil Davis
	if (isset($userindex[$name])) {
275 55eb9c44 --global
		return $config['system']['user'][$userindex[$name]];
276 1e0b1727 Phil Davis
	}
277 55eb9c44 --global
}
278
279
function & getUserEntryByUID($uid) {
280
	global $debug, $config;
281 84924e76 Ermal
282 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
283
		foreach ($config['system']['user'] as & $user) {
284
			if ($user['uid'] == $uid) {
285 84924e76 Ermal
				return $user;
286 1e0b1727 Phil Davis
			}
287
		}
288
	}
289 55eb9c44 --global
290
	return false;
291
}
292
293
function & getGroupEntry($name) {
294
	global $debug, $config, $groupindex;
295 1e0b1727 Phil Davis
	if (isset($groupindex[$name])) {
296 55eb9c44 --global
		return $config['system']['group'][$groupindex[$name]];
297 1e0b1727 Phil Davis
	}
298 55eb9c44 --global
}
299
300
function & getGroupEntryByGID($gid) {
301
	global $debug, $config;
302 84924e76 Ermal
303 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
304
		foreach ($config['system']['group'] as & $group) {
305
			if ($group['gid'] == $gid) {
306 84924e76 Ermal
				return $group;
307 1e0b1727 Phil Davis
			}
308
		}
309
	}
310 55eb9c44 --global
311
	return false;
312
}
313
314 6dc88d53 Ermal Luci
function get_user_privileges(& $user) {
315
316 1e0b1727 Phil Davis
	$privs = $user['priv'];
317
	if (!is_array($privs)) {
318
		$privs = array();
319
	}
320 6dc88d53 Ermal Luci
321 1e0b1727 Phil Davis
	$names = local_user_get_groups($user, true);
322 6dc88d53 Ermal Luci
323 1e0b1727 Phil Davis
	foreach ($names as $name) {
324
		$group = getGroupEntry($name);
325
		if (is_array($group['priv'])) {
326 4de8f7ba Phil Davis
			$privs = array_merge($privs, $group['priv']);
327 1e0b1727 Phil Davis
		}
328
	}
329 6dc88d53 Ermal Luci
330 1e0b1727 Phil Davis
	return $privs;
331 6dc88d53 Ermal Luci
}
332
333
function userHasPrivilege($userent, $privid = false) {
334
335 1e0b1727 Phil Davis
	if (!$privid || !is_array($userent)) {
336
		return false;
337
	}
338 6dc88d53 Ermal Luci
339 1e0b1727 Phil Davis
	$privs = get_user_privileges($userent);
340 6dc88d53 Ermal Luci
341 1e0b1727 Phil Davis
	if (!is_array($privs)) {
342
		return false;
343
	}
344 6dc88d53 Ermal Luci
345 1e0b1727 Phil Davis
	if (!in_array($privid, $privs)) {
346
		return false;
347
	}
348 6dc88d53 Ermal Luci
349 1e0b1727 Phil Davis
	return true;
350 6dc88d53 Ermal Luci
}
351
352 55eb9c44 --global
function local_backed($username, $passwd) {
353
354
	$user = getUserEntry($username);
355 1e0b1727 Phil Davis
	if (!$user) {
356 55eb9c44 --global
		return false;
357 1e0b1727 Phil Davis
	}
358 55eb9c44 --global
359 1e0b1727 Phil Davis
	if (is_account_disabled($username) || is_account_expired($username)) {
360 a13ce628 Ermal Lu?i
		return false;
361 1e0b1727 Phil Davis
	}
362 a13ce628 Ermal Lu?i
363 9219378b daniel
	if ($user['bcrypt-hash']) {
364
		if (password_verify($passwd, $user['bcrypt-hash'])) {
365
			return true;
366
		}
367
	}
368
369
	//for backwards compatibility
370 1e0b1727 Phil Davis
	if ($user['password']) {
371
		if (crypt($passwd, $user['password']) == $user['password']) {
372 55eb9c44 --global
			return true;
373 1e0b1727 Phil Davis
		}
374 55eb9c44 --global
	}
375
376 1e0b1727 Phil Davis
	if ($user['md5-hash']) {
377
		if (md5($passwd) == $user['md5-hash']) {
378 55eb9c44 --global
			return true;
379 1e0b1727 Phil Davis
		}
380 55eb9c44 --global
	}
381
382
	return false;
383
}
384
385
function local_sync_accounts() {
386
	global $debug, $config;
387
	conf_mount_rw();
388
389
	/* remove local users to avoid uid conflicts */
390
	$fd = popen("/usr/sbin/pw usershow -a", "r");
391
	if ($fd) {
392
		while (!feof($fd)) {
393 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
394 1e0b1727 Phil Davis
			if (((!strncmp($line[0], "_", 1)) || ($line[2] < 2000) || ($line[2] > 65000)) && ($line[0] != "admin")) {
395 55eb9c44 --global
				continue;
396 1e0b1727 Phil Davis
			}
397 2b41df9c Renato Botelho
			/*
398
			 * If a crontab was created to user, pw userdel will be interactive and
399
			 * can cause issues. Just remove crontab before run it when necessary
400
			 */
401
			unlink_if_exists("/var/cron/tabs/{$line[0]}");
402 0f84dee3 Renato Botelho
			$cmd = "/usr/sbin/pw userdel -n '{$line[0]}'";
403 1e0b1727 Phil Davis
			if ($debug) {
404 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
405 1e0b1727 Phil Davis
			}
406 55eb9c44 --global
			mwexec($cmd);
407
		}
408
		pclose($fd);
409
	}
410
411
	/* remove local groups to avoid gid conflicts */
412
	$gids = array();
413
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
414
	if ($fd) {
415
		while (!feof($fd)) {
416 4de8f7ba Phil Davis
			$line = explode(":", fgets($fd));
417 1e0b1727 Phil Davis
			if (!strncmp($line[0], "_", 1)) {
418 55eb9c44 --global
				continue;
419 1e0b1727 Phil Davis
			}
420
			if ($line[2] < 2000) {
421 55eb9c44 --global
				continue;
422 1e0b1727 Phil Davis
			}
423
			if ($line[2] > 65000) {
424 55eb9c44 --global
				continue;
425 1e0b1727 Phil Davis
			}
426 55eb9c44 --global
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
427 1e0b1727 Phil Davis
			if ($debug) {
428 94021404 Carlos Eduardo Ramos
				log_error(sprintf(gettext("Running: %s"), $cmd));
429 1e0b1727 Phil Davis
			}
430 55eb9c44 --global
			mwexec($cmd);
431
		}
432
		pclose($fd);
433
	}
434
435
	/* make sure the all group exists */
436
	$allgrp = getGroupEntryByGID(1998);
437
	local_group_set($allgrp, true);
438
439 5af2baf7 jim-p
	/* sync all local users */
440 1e0b1727 Phil Davis
	if (is_array($config['system']['user'])) {
441
		foreach ($config['system']['user'] as $user) {
442 5af2baf7 jim-p
			local_user_set($user);
443 1e0b1727 Phil Davis
		}
444
	}
445 5af2baf7 jim-p
446 f3e0a111 jim-p
	/* sync all local groups */
447 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
448
		foreach ($config['system']['group'] as $group) {
449 f3e0a111 jim-p
			local_group_set($group);
450 1e0b1727 Phil Davis
		}
451
	}
452 f3e0a111 jim-p
453 55eb9c44 --global
	conf_mount_ro();
454
455
}
456
457
function local_user_set(& $user) {
458
	global $g, $debug;
459
460 9219378b daniel
	if (empty($user['password']) && empty($user['bcrypt-hash'])) {
461 b3c106a0 Ermal
		log_error("There is something wrong in your config because user {$user['name']} password is missing!");
462
		return;
463
	}
464
465 2bb07efc Scott Ullrich
	conf_mount_rw();
466
467 1180e4f0 Sjon Hortensius
	$home_base = "/home/";
468 55eb9c44 --global
	$user_uid = $user['uid'];
469
	$user_name = $user['name'];
470 461df7c0 jim-p
	$user_home = "{$home_base}{$user_name}";
471 55eb9c44 --global
	$user_shell = "/etc/rc.initial";
472
	$user_group = "nobody";
473
474
	// Ensure $home_base exists and is writable
475 1e0b1727 Phil Davis
	if (!is_dir($home_base)) {
476 55eb9c44 --global
		mkdir($home_base, 0755);
477 1e0b1727 Phil Davis
	}
478 55eb9c44 --global
479 df8d74de jim-p
	$lock_account = false;
480 55eb9c44 --global
	/* configure shell type */
481 3e251b12 Erik Fonnesbeck
	/* Cases here should be ordered by most privileged to least privileged. */
482 a137fedd jim-p
	if (userHasPrivilege($user, "user-shell-access") || userHasPrivilege($user, "page-all")) {
483 29293dce jim-p
		$user_shell = "/bin/tcsh";
484 1ed86bc6 jim-p
	} elseif (userHasPrivilege($user, "user-copy-files")) {
485 a137fedd jim-p
		$user_shell = "/usr/local/bin/scponly";
486 3e251b12 Erik Fonnesbeck
	} elseif (userHasPrivilege($user, "user-ssh-tunnel")) {
487
		$user_shell = "/usr/local/sbin/ssh_tunnel_shell";
488 fbfd675a jim-p
	} elseif (userHasPrivilege($user, "user-ipsec-xauth-dialin")) {
489
		$user_shell = "/sbin/nologin";
490 1ed86bc6 jim-p
	} else {
491
		$user_shell = "/sbin/nologin";
492 df8d74de jim-p
		$lock_account = true;
493
	}
494
495
	/* Lock out disabled or expired users, unless it's root/admin. */
496
	if ((is_account_disabled($user_name) || is_account_expired($user_name)) && ($user_uid != 0)) {
497
		$user_shell = "/sbin/nologin";
498
		$lock_account = true;
499 55eb9c44 --global
	}
500
501
	/* root user special handling */
502
	if ($user_uid == 0) {
503
		$cmd = "/usr/sbin/pw usermod -q -n root -s /bin/sh -H 0";
504 1e0b1727 Phil Davis
		if ($debug) {
505 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Running: %s"), $cmd));
506 1e0b1727 Phil Davis
		}
507 55eb9c44 --global
		$fd = popen($cmd, "w");
508 9219378b daniel
		if (empty($user['bcrypt-hash'])) {
509
			fwrite($fd, $user['password']);
510 9a7911eb Daniel Vinakovsky
		} else {
511 9219378b daniel
			fwrite($fd, $user['bcrypt-hash']);
512
		}
513 55eb9c44 --global
		pclose($fd);
514
		$user_group = "wheel";
515 2708e399 jim-p
		$user_home = "/root";
516 29293dce jim-p
		$user_shell = "/etc/rc.initial";
517 55eb9c44 --global
	}
518
519
	/* read from pw db */
520 9fd14591 jim-p
	$fd = popen("/usr/sbin/pw usershow -n {$user_name} 2>&1", "r");
521 55eb9c44 --global
	$pwread = fgets($fd);
522
	pclose($fd);
523 9fd14591 jim-p
	$userattrs = explode(":", trim($pwread));
524 55eb9c44 --global
525
	/* determine add or mod */
526 9fd14591 jim-p
	if (($userattrs[0] != $user['name']) || (!strncmp($pwread, "pw:", 3))) {
527 4b49a8a9 jim-p
		$user_op = "useradd -m -k /etc/skel -o";
528 38564fde smos
	} else {
529 55eb9c44 --global
		$user_op = "usermod";
530 38564fde smos
	}
531 55eb9c44 --global
532 1180e4f0 Sjon Hortensius
	$comment = str_replace(array(":", "!", "@"), " ", $user['descr']);
533 55eb9c44 --global
	/* add or mod pw db */
534
	$cmd = "/usr/sbin/pw {$user_op} -q -u {$user_uid} -n {$user_name}".
535 eb72845c jim-p
			" -g {$user_group} -s {$user_shell} -d {$user_home}".
536 1cb94b24 Ermal
			" -c ".escapeshellarg($comment)." -H 0 2>&1";
537 55eb9c44 --global
538 1e0b1727 Phil Davis
	if ($debug) {
539 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
540 1e0b1727 Phil Davis
	}
541 55eb9c44 --global
	$fd = popen($cmd, "w");
542 9219378b daniel
	if (empty($user['bcrypt-hash'])) {
543
		fwrite($fd, $user['password']);
544 9a7911eb Daniel Vinakovsky
	} else {
545 9219378b daniel
		fwrite($fd, $user['bcrypt-hash']);
546
	}
547 55eb9c44 --global
	pclose($fd);
548
549
	/* create user directory if required */
550
	if (!is_dir($user_home)) {
551
		mkdir($user_home, 0700);
552
	}
553 23c652cd Ermal
	@chown($user_home, $user_name);
554
	@chgrp($user_home, $user_group);
555 55eb9c44 --global
556
	/* write out ssh authorized key file */
557 1e0b1727 Phil Davis
	if ($user['authorizedkeys']) {
558 a2286360 Ermal Lu?i
		if (!is_dir("{$user_home}/.ssh")) {
559 23c652cd Ermal
			@mkdir("{$user_home}/.ssh", 0700);
560
			@chown("{$user_home}/.ssh", $user_name);
561 a2286360 Ermal Lu?i
		}
562
		$keys = base64_decode($user['authorizedkeys']);
563 23c652cd Ermal
		@file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
564
		@chown("{$user_home}/.ssh/authorized_keys", $user_name);
565 1e0b1727 Phil Davis
	} else {
566 cdab65cc Erik Fonnesbeck
		unlink_if_exists("{$user_home}/.ssh/authorized_keys");
567 1e0b1727 Phil Davis
	}
568 df8d74de jim-p
569
	$un = $lock_account ? "" : "un";
570 e4d09dca Renato Botelho
	exec("/usr/sbin/pw {$un}lock {$user_name} -q 2>/dev/null");
571 1180e4f0 Sjon Hortensius
572 2bb07efc Scott Ullrich
	conf_mount_ro();
573 55eb9c44 --global
}
574
575
function local_user_del($user) {
576
	global $debug;
577 2bb07efc Scott Ullrich
578 55eb9c44 --global
	/* remove all memberships */
579 019e6c3f jim-p
	local_user_set_groups($user);
580 55eb9c44 --global
581 a39675ec jim-p
	/* Don't remove /root */
582 1e0b1727 Phil Davis
	if ($user['uid'] != 0) {
583 a39675ec jim-p
		$rmhome = "-r";
584 1e0b1727 Phil Davis
	}
585 a39675ec jim-p
586 9fd14591 jim-p
	/* read from pw db */
587
	$fd = popen("/usr/sbin/pw usershow -n {$user['name']} 2>&1", "r");
588
	$pwread = fgets($fd);
589
	pclose($fd);
590
	$userattrs = explode(":", trim($pwread));
591
592
	if ($userattrs[0] != $user['name']) {
593
		log_error("Tried to remove user {$user['name']} but got user {$userattrs[0]} instead. Bailing.");
594
		return;
595
	}
596
597 55eb9c44 --global
	/* delete from pw db */
598 9fd14591 jim-p
	$cmd = "/usr/sbin/pw userdel -n {$user['name']} {$rmhome}";
599 55eb9c44 --global
600 1e0b1727 Phil Davis
	if ($debug) {
601 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
602 1e0b1727 Phil Davis
	}
603 0914b6bb Ermal
	mwexec($cmd);
604 2bb07efc Scott Ullrich
605 0914b6bb Ermal
	/* Delete user from groups needs a call to write_config() */
606
	local_group_del_user($user);
607 55eb9c44 --global
}
608
609 4d9801c2 Jim Thompson
function local_user_set_password(&$user, $password) {
610 55eb9c44 --global
611 33386b07 Daniel Vinakovsky
	unset($user['password']);
612
	unset($user['md5-hash']);
613
	$user['bcrypt-hash'] = password_hash($password, PASSWORD_BCRYPT);
614 55eb9c44 --global
615 4d4e9a11 Daniel Vinakovsky
	/* Maintain compatibility with FreeBSD - change $2y$ prefix to $2b$
616
	 * https://reviews.freebsd.org/D2742
617 6fadbf9b Dan Vinakovsky
	 * XXX: Can be removed as soon as r284483 is MFC'd.
618 4d4e9a11 Daniel Vinakovsky
	 */
619 4b737f6e Daniel Vinakovsky
	if ($user['bcrypt-hash'][2] == "y") {
620
		$user['bcrypt-hash'][2] = "b";
621
	}
622
623 55eb9c44 --global
	// Converts ascii to unicode.
624
	$astr = (string) $password;
625
	$ustr = '';
626
	for ($i = 0; $i < strlen($astr); $i++) {
627
		$a = ord($astr{$i}) << 8;
628 4de8f7ba Phil Davis
		$ustr .= sprintf("%X", $a);
629 55eb9c44 --global
	}
630
631
}
632
633
function local_user_get_groups($user, $all = false) {
634
	global $debug, $config;
635
636
	$groups = array();
637 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
638 55eb9c44 --global
		return $groups;
639 1e0b1727 Phil Davis
	}
640 55eb9c44 --global
641 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
642 4de8f7ba Phil Davis
		if ($all || (!$all && ($group['name'] != "all"))) {
643 1e0b1727 Phil Davis
			if (is_array($group['member'])) {
644
				if (in_array($user['uid'], $group['member'])) {
645 55eb9c44 --global
					$groups[] = $group['name'];
646 1e0b1727 Phil Davis
				}
647
			}
648
		}
649
	}
650 55eb9c44 --global
651 1e0b1727 Phil Davis
	if ($all) {
652 b0c231e4 jim-p
		$groups[] = "all";
653 1e0b1727 Phil Davis
	}
654 b0c231e4 jim-p
655 55eb9c44 --global
	sort($groups);
656
657
	return $groups;
658 1180e4f0 Sjon Hortensius
659 55eb9c44 --global
}
660
661 4de8f7ba Phil Davis
function local_user_set_groups($user, $new_groups = NULL) {
662 55eb9c44 --global
	global $debug, $config, $groupindex;
663 4de8f7ba Phil Davis
664 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
665 55eb9c44 --global
		return;
666 1e0b1727 Phil Davis
	}
667 55eb9c44 --global
668 739c78ac jim-p
	$cur_groups = local_user_get_groups($user, true);
669 55eb9c44 --global
	$mod_groups = array();
670
671 1e0b1727 Phil Davis
	if (!is_array($new_groups)) {
672 55eb9c44 --global
		$new_groups = array();
673 1e0b1727 Phil Davis
	}
674 55eb9c44 --global
675 1e0b1727 Phil Davis
	if (!is_array($cur_groups)) {
676 55eb9c44 --global
		$cur_groups = array();
677 1e0b1727 Phil Davis
	}
678 55eb9c44 --global
679
	/* determine which memberships to add */
680
	foreach ($new_groups as $groupname) {
681 4de8f7ba Phil Davis
		if ($groupname == '' || in_array($groupname, $cur_groups)) {
682 55eb9c44 --global
			continue;
683 1e0b1727 Phil Davis
		}
684 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
685
		$group['member'][] = $user['uid'];
686
		$mod_groups[] = $group;
687
	}
688 9ae11a62 Scott Ullrich
	unset($group);
689 55eb9c44 --global
690
	/* determine which memberships to remove */
691
	foreach ($cur_groups as $groupname) {
692 4de8f7ba Phil Davis
		if (in_array($groupname, $new_groups)) {
693 e879fc81 Ermal
			continue;
694 1e0b1727 Phil Davis
		}
695
		if (!isset($config['system']['group'][$groupindex[$groupname]])) {
696 25fec9b3 jim-p
			continue;
697 1e0b1727 Phil Davis
		}
698 55eb9c44 --global
		$group = & $config['system']['group'][$groupindex[$groupname]];
699 7b5c56ea jim-p
		if (is_array($group['member'])) {
700
			$index = array_search($user['uid'], $group['member']);
701
			array_splice($group['member'], $index, 1);
702
			$mod_groups[] = $group;
703
		}
704 55eb9c44 --global
	}
705 9ae11a62 Scott Ullrich
	unset($group);
706 55eb9c44 --global
707
	/* sync all modified groups */
708 1e0b1727 Phil Davis
	foreach ($mod_groups as $group) {
709 55eb9c44 --global
		local_group_set($group);
710 1e0b1727 Phil Davis
	}
711 55eb9c44 --global
}
712
713 0914b6bb Ermal
function local_group_del_user($user) {
714
	global $config;
715
716 1e0b1727 Phil Davis
	if (!is_array($config['system']['group'])) {
717
		return;
718
	}
719 0914b6bb Ermal
720 1e0b1727 Phil Davis
	foreach ($config['system']['group'] as $group) {
721 0914b6bb Ermal
		if (is_array($group['member'])) {
722
			foreach ($group['member'] as $idx => $uid) {
723 1e0b1727 Phil Davis
				if ($user['uid'] == $uid) {
724 0914b6bb Ermal
					unset($config['system']['group']['member'][$idx]);
725 1e0b1727 Phil Davis
				}
726 0914b6bb Ermal
			}
727
		}
728
	}
729
}
730
731 55eb9c44 --global
function local_group_set($group, $reset = false) {
732
	global $debug;
733
734
	$group_name = $group['name'];
735
	$group_gid = $group['gid'];
736 baca968c Ermal
	$group_members = '';
737 1e0b1727 Phil Davis
	if (!$reset && !empty($group['member']) && count($group['member']) > 0) {
738 4de8f7ba Phil Davis
		$group_members = implode(",", $group['member']);
739 1e0b1727 Phil Davis
	}
740 55eb9c44 --global
741 1e0b1727 Phil Davis
	if (empty($group_name)) {
742 baca968c Ermal
		return;
743 1e0b1727 Phil Davis
	}
744 baca968c Ermal
745 55eb9c44 --global
	/* read from group db */
746
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
747
	$pwread = fgets($fd);
748
	pclose($fd);
749
750
	/* determine add or mod */
751 1e0b1727 Phil Davis
	if (!strncmp($pwread, "pw:", 3)) {
752 55eb9c44 --global
		$group_op = "groupadd";
753 1e0b1727 Phil Davis
	} else {
754 55eb9c44 --global
		$group_op = "groupmod";
755 1e0b1727 Phil Davis
	}
756 55eb9c44 --global
757
	/* add or mod group db */
758 224b4208 Renato Botelho
	$cmd = "/usr/sbin/pw {$group_op} {$group_name} -g {$group_gid} -M '{$group_members}' 2>&1";
759 55eb9c44 --global
760 1e0b1727 Phil Davis
	if ($debug) {
761 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
762 1e0b1727 Phil Davis
	}
763 0914b6bb Ermal
	mwexec($cmd);
764 55eb9c44 --global
765
}
766
767
function local_group_del($group) {
768
	global $debug;
769
770
	/* delete from group db */
771
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
772
773 1e0b1727 Phil Davis
	if ($debug) {
774 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("Running: %s"), $cmd));
775 1e0b1727 Phil Davis
	}
776 0914b6bb Ermal
	mwexec($cmd);
777 55eb9c44 --global
}
778
779 6306b5dd Ermal Lu?i
function ldap_test_connection($authcfg) {
780 55eb9c44 --global
	global $debug, $config, $g;
781
782 c61e4626 Ermal Lu?i
	if ($authcfg) {
783 1e0b1727 Phil Davis
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
784
			$ldapproto = "ldap";
785
		} else {
786
			$ldapproto = "ldaps";
787
		}
788
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
789
		$ldapport = $authcfg['ldap_port'];
790
		if (!empty($ldapport)) {
791 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
792 1e0b1727 Phil Davis
		}
793
		$ldapbasedn = $authcfg['ldap_basedn'];
794
		$ldapbindun = $authcfg['ldap_binddn'];
795
		$ldapbindpw = $authcfg['ldap_bindpw'];
796
	} else {
797 6306b5dd Ermal Lu?i
		return false;
798 1e0b1727 Phil Davis
	}
799 55eb9c44 --global
800 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
801 4de8f7ba Phil Davis
	if (!$ldapserver) {
802 1e0b1727 Phil Davis
		return false;
803
	}
804 c61e4626 Ermal Lu?i
805 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
806
	ldap_setup_caenv($authcfg);
807 fe2031ab Ermal
808 1e0b1727 Phil Davis
	/* connect and see if server is up */
809
	$error = false;
810
	if (!($ldap = ldap_connect($ldapserver))) {
811 9f27de6d jim-p
		$error = true;
812 1e0b1727 Phil Davis
	}
813 c61e4626 Ermal Lu?i
814 1e0b1727 Phil Davis
	if ($error == true) {
815
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
816
		return false;
817
	}
818 55eb9c44 --global
819
	return true;
820
}
821
822 fe2031ab Ermal
function ldap_setup_caenv($authcfg) {
823
	global $g;
824 007e59d2 jim-p
	require_once("certs.inc");
825 fe2031ab Ermal
826
	unset($caref);
827 a7702ed5 Ermal
	if (empty($authcfg['ldap_caref']) || !strstr($authcfg['ldap_urltype'], "SSL")) {
828 fe2031ab Ermal
		putenv('LDAPTLS_REQCERT=never');
829
		return;
830
	} else {
831 a7702ed5 Ermal
		$caref = lookup_ca($authcfg['ldap_caref']);
832 fe2031ab Ermal
		if (!$caref) {
833 a7702ed5 Ermal
			log_error(sprintf(gettext("LDAP: Could not lookup CA by reference for host %s."), $authcfg['ldap_caref']));
834 fe2031ab Ermal
			/* XXX: Prevent for credential leaking since we cannot setup the CA env. Better way? */
835
			putenv('LDAPTLS_REQCERT=hard');
836
			return;
837
		}
838 1e0b1727 Phil Davis
		if (!is_dir("{$g['varrun_path']}/certs")) {
839 fe2031ab Ermal
			@mkdir("{$g['varrun_path']}/certs");
840 1e0b1727 Phil Davis
		}
841
		if (file_exists("{$g['varrun_path']}/certs/{$caref['refid']}.ca")) {
842 b2a0a8e9 jim-p
			@unlink("{$g['varrun_path']}/certs/{$caref['refid']}.ca");
843 1e0b1727 Phil Davis
		}
844 b2a0a8e9 jim-p
		file_put_contents("{$g['varrun_path']}/certs/{$caref['refid']}.ca", base64_decode($caref['crt']));
845
		@chmod("{$g['varrun_path']}/certs/{$caref['refid']}.ca", 0600);
846 fe2031ab Ermal
		putenv('LDAPTLS_REQCERT=hard');
847
		/* XXX: Probably even the hashed link should be created for this? */
848 906daddc Ermal
		putenv("LDAPTLS_CACERTDIR={$g['varrun_path']}/certs");
849 b2a0a8e9 jim-p
		putenv("LDAPTLS_CACERT={$g['varrun_path']}/certs/{$caref['refid']}.ca");
850 fe2031ab Ermal
	}
851
}
852
853 6306b5dd Ermal Lu?i
function ldap_test_bind($authcfg) {
854 55eb9c44 --global
	global $debug, $config, $g;
855
856 c61e4626 Ermal Lu?i
	if ($authcfg) {
857 1e0b1727 Phil Davis
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
858
			$ldapproto = "ldap";
859
		} else {
860
			$ldapproto = "ldaps";
861
		}
862
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
863
		$ldapport = $authcfg['ldap_port'];
864
		if (!empty($ldapport)) {
865 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
866 1e0b1727 Phil Davis
		}
867
		$ldapbasedn = $authcfg['ldap_basedn'];
868
		$ldapbindun = $authcfg['ldap_binddn'];
869
		$ldapbindpw = $authcfg['ldap_bindpw'];
870
		$ldapver = $authcfg['ldap_protver'];
871 d6b4dfe3 jim-p
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
872 1e0b1727 Phil Davis
		if (empty($ldapbndun) || empty($ldapbindpw)) {
873
			$ldapanon = true;
874
		} else {
875
			$ldapanon = false;
876
		}
877
	} else {
878 6306b5dd Ermal Lu?i
		return false;
879 1e0b1727 Phil Davis
	}
880 c61e4626 Ermal Lu?i
881
	/* first check if there is even an LDAP server populated */
882 1e0b1727 Phil Davis
	if (!$ldapserver) {
883
		return false;
884
	}
885 c61e4626 Ermal Lu?i
886 fe2031ab Ermal
	/* Setup CA environment if needed. */
887
	ldap_setup_caenv($authcfg);
888
889 1e0b1727 Phil Davis
	/* connect and see if server is up */
890
	$error = false;
891
	if (!($ldap = ldap_connect($ldapserver))) {
892 9f27de6d jim-p
		$error = true;
893 1e0b1727 Phil Davis
	}
894 c61e4626 Ermal Lu?i
895 1e0b1727 Phil Davis
	if ($error == true) {
896
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
897
		return false;
898
	}
899 55eb9c44 --global
900
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
901 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
902 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
903 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
904
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
905 1180e4f0 Sjon Hortensius
906 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
907
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
908 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
909 6306b5dd Ermal Lu?i
		if (!($res = @ldap_bind($ldap))) {
910
			@ldap_close($ldap);
911 c61e4626 Ermal Lu?i
			return false;
912 6306b5dd Ermal Lu?i
		}
913
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
914
		@ldap_close($ldap);
915 55eb9c44 --global
		return false;
916 6306b5dd Ermal Lu?i
	}
917 55eb9c44 --global
918 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
919 c61e4626 Ermal Lu?i
920 55eb9c44 --global
	return true;
921
}
922
923 6306b5dd Ermal Lu?i
function ldap_get_user_ous($show_complete_ou=true, $authcfg) {
924 55eb9c44 --global
	global $debug, $config, $g;
925
926 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
927 55eb9c44 --global
		return;
928 1e0b1727 Phil Davis
	}
929 55eb9c44 --global
930 7a938f1b Ermal
	$ous = array();
931
932 c61e4626 Ermal Lu?i
	if ($authcfg) {
933 1e0b1727 Phil Davis
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
934
			$ldapproto = "ldap";
935
		} else {
936
			$ldapproto = "ldaps";
937
		}
938
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
939
		$ldapport = $authcfg['ldap_port'];
940
		if (!empty($ldapport)) {
941 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
942 1e0b1727 Phil Davis
		}
943
		$ldapbasedn = $authcfg['ldap_basedn'];
944
		$ldapbindun = $authcfg['ldap_binddn'];
945
		$ldapbindpw = $authcfg['ldap_bindpw'];
946
		$ldapver = $authcfg['ldap_protver'];
947
		if (empty($ldapbindun) || empty($ldapbindpw)) {
948
			$ldapanon = true;
949
		} else {
950
			$ldapanon = false;
951
		}
952
		$ldapname = $authcfg['name'];
953
		$ldapfallback = false;
954
		$ldapscope = $authcfg['ldap_scope'];
955 d6b4dfe3 jim-p
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
956 1e0b1727 Phil Davis
	} else {
957 6306b5dd Ermal Lu?i
		return false;
958 1e0b1727 Phil Davis
	}
959 55eb9c44 --global
960 1e0b1727 Phil Davis
	/* first check if there is even an LDAP server populated */
961
	if (!$ldapserver) {
962
		log_error(gettext("ERROR!  ldap_get_user_ous() backed selected with no LDAP authentication server defined."));
963
		return $ous;
964
	}
965 c61e4626 Ermal Lu?i
966 fe2031ab Ermal
	/* Setup CA environment if needed. */
967
	ldap_setup_caenv($authcfg);
968
969 c61e4626 Ermal Lu?i
	/* connect and see if server is up */
970 1e0b1727 Phil Davis
	$error = false;
971
	if (!($ldap = ldap_connect($ldapserver))) {
972 9f27de6d jim-p
		$error = true;
973 1e0b1727 Phil Davis
	}
974 c61e4626 Ermal Lu?i
975 1e0b1727 Phil Davis
	if ($error == true) {
976
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
977
		return $ous;
978
	}
979 c61e4626 Ermal Lu?i
980
	$ldapfilter = "(|(ou=*)(cn=Users))";
981 55eb9c44 --global
982
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
983 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
984 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
985 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
986
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
987 55eb9c44 --global
988 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
989
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
990 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
991 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
992 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind anonymously to server %s."), $ldapname));
993 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
994 1e0b1727 Phil Davis
			return $ous;
995 c61e4626 Ermal Lu?i
		}
996
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
997 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_user_ous() could not bind to server %s."), $ldapname));
998 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
999 c61e4626 Ermal Lu?i
		return $ous;
1000 55eb9c44 --global
	}
1001
1002 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1003 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_list";
1004 1e0b1727 Phil Davis
	} else {
1005 c61e4626 Ermal Lu?i
		$ldapfunc = "ldap_search";
1006 1e0b1727 Phil Davis
	}
1007 55eb9c44 --global
1008 7a938f1b Ermal
	$search = @$ldapfunc($ldap, $ldapbasedn, $ldapfilter);
1009
	$info = @ldap_get_entries($ldap, $search);
1010 55eb9c44 --global
1011
	if (is_array($info)) {
1012
		foreach ($info as $inf) {
1013
			if (!$show_complete_ou) {
1014 cfbfd941 smos
				$inf_split = explode(",", $inf['dn']);
1015 55eb9c44 --global
				$ou = $inf_split[0];
1016 4de8f7ba Phil Davis
				$ou = str_replace("OU=", "", $ou);
1017
				$ou = str_replace("CN=", "", $ou);
1018 1e0b1727 Phil Davis
			} else {
1019
				if ($inf['dn']) {
1020 55eb9c44 --global
					$ou = $inf['dn'];
1021 1e0b1727 Phil Davis
				}
1022
			}
1023
			if ($ou) {
1024 55eb9c44 --global
				$ous[] = $ou;
1025 1e0b1727 Phil Davis
			}
1026 55eb9c44 --global
		}
1027
	}
1028
1029 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1030
1031 55eb9c44 --global
	return $ous;
1032
}
1033
1034 6306b5dd Ermal Lu?i
function ldap_get_groups($username, $authcfg) {
1035 55eb9c44 --global
	global $debug, $config;
1036 1180e4f0 Sjon Hortensius
1037 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1038 55eb9c44 --global
		return;
1039 1e0b1727 Phil Davis
	}
1040 1180e4f0 Sjon Hortensius
1041 1e0b1727 Phil Davis
	if (!$username) {
1042 55eb9c44 --global
		return false;
1043 1e0b1727 Phil Davis
	}
1044 55eb9c44 --global
1045 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1046 2ce660ad smos
		$username_split = explode("@", $username);
1047 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1048 55eb9c44 --global
	}
1049
1050 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1051 cfbfd941 smos
		$username_split = explode("\\", $username);
1052 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1053
	}
1054
1055 55eb9c44 --global
	//log_error("Getting LDAP groups for {$username}.");
1056 1e0b1727 Phil Davis
	if ($authcfg) {
1057
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
1058
			$ldapproto = "ldap";
1059
		} else {
1060
			$ldapproto = "ldaps";
1061
		}
1062
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1063
		$ldapport = $authcfg['ldap_port'];
1064
		if (!empty($ldapport)) {
1065 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1066 1e0b1727 Phil Davis
		}
1067
		$ldapbasedn = $authcfg['ldap_basedn'];
1068
		$ldapbindun = $authcfg['ldap_binddn'];
1069
		$ldapbindpw = $authcfg['ldap_bindpw'];
1070
		$ldapauthcont = $authcfg['ldap_authcn'];
1071
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1072
		$ldapgroupattribute = strtolower($authcfg['ldap_attr_member']);
1073 149efbea jim-p
		if (isset($authcfg['ldap_rfc2307'])) {
1074
			$ldapfilter         = "(&(objectClass={$authcfg['ldap_attr_groupobj']})({$ldapgroupattribute}={$username}))";
1075
		} else {
1076
			$ldapfilter         = "({$ldapnameattribute}={$username})";
1077
		}
1078 1e0b1727 Phil Davis
		$ldaptype = "";
1079
		$ldapver = $authcfg['ldap_protver'];
1080
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1081
			$ldapanon = true;
1082
		} else {
1083
			$ldapanon = false;
1084
		}
1085
		$ldapname = $authcfg['name'];
1086
		$ldapfallback = false;
1087
		$ldapscope = $authcfg['ldap_scope'];
1088 d6b4dfe3 jim-p
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
1089 1e0b1727 Phil Davis
	} else {
1090 6306b5dd Ermal Lu?i
		return false;
1091 1e0b1727 Phil Davis
	}
1092 c61e4626 Ermal Lu?i
1093 149efbea jim-p
	if (isset($authcfg['ldap_rfc2307'])) {
1094
		$ldapdn = $ldapbasedn;
1095
	} else {
1096
		$ldapdn = $_SESSION['ldapdn'];
1097
	}
1098 c61e4626 Ermal Lu?i
1099 55eb9c44 --global
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
1100
	$ldapgroupattribute = strtolower($ldapgroupattribute);
1101 c61e4626 Ermal Lu?i
	$memberof = array();
1102 55eb9c44 --global
1103 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
1104
	ldap_setup_caenv($authcfg);
1105 fe2031ab Ermal
1106 55eb9c44 --global
	/* connect and see if server is up */
1107 c61e4626 Ermal Lu?i
	$error = false;
1108 1e0b1727 Phil Davis
	if (!($ldap = ldap_connect($ldapserver))) {
1109 9f27de6d jim-p
		$error = true;
1110 1e0b1727 Phil Davis
	}
1111 c61e4626 Ermal Lu?i
1112
	if ($error == true) {
1113 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() Could not connect to server %s."), $ldapname));
1114 1e0b1727 Phil Davis
		return memberof;
1115
	}
1116 1180e4f0 Sjon Hortensius
1117 55eb9c44 --global
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1118 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1119 c61e4626 Ermal Lu?i
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1120 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1121
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1122 55eb9c44 --global
1123
	/* bind as user that has rights to read group attributes */
1124 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1125
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1126 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1127 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1128 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind anonymously to server %s."), $ldapname));
1129 6306b5dd Ermal Lu?i
			@ldap_close($ldap);
1130 1e0b1727 Phil Davis
			return false;
1131 6306b5dd Ermal Lu?i
		}
1132 c61e4626 Ermal Lu?i
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1133 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! ldap_get_groups() could not bind to server %s."), $ldapname));
1134 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1135 c61e4626 Ermal Lu?i
		return memberof;
1136 55eb9c44 --global
	}
1137
1138
	/* get groups from DN found */
1139
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
1140
	/* since we know the DN is in $_SESSION['ldapdn'] */
1141
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
1142 1e0b1727 Phil Davis
	if ($ldapscope == "one") {
1143
		$ldapfunc = "ldap_list";
1144
	} else {
1145
		$ldapfunc = "ldap_search";
1146
	}
1147 c61e4626 Ermal Lu?i
1148 1e0b1727 Phil Davis
	$search = @$ldapfunc($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
1149
	$info = @ldap_get_entries($ldap, $search);
1150 55eb9c44 --global
1151 149efbea jim-p
	$gresults = isset($authcfg['ldap_rfc2307']) ? $info : $info[0][$ldapgroupattribute];
1152 1180e4f0 Sjon Hortensius
1153 4e322e2c Phil Davis
	if (is_array($gresults)) {
1154 55eb9c44 --global
		/* Iterate through the groups and throw them into an array */
1155 149efbea jim-p
		foreach ($gresults as $grp) {
1156 4e322e2c Phil Davis
			if (((isset($authcfg['ldap_rfc2307'])) && (stristr($grp["dn"], "CN=") !== false)) ||
1157
			    ((!isset($authcfg['ldap_rfc2307'])) && (stristr($grp, "CN=") !== false))) {
1158 149efbea jim-p
				$grpsplit = isset($authcfg['ldap_rfc2307']) ? explode(",", $grp["dn"]) : explode(",", $grp);
1159
				$memberof[] = preg_replace("/CN=/i", "", $grpsplit[0]);
1160 55eb9c44 --global
			}
1161
		}
1162
	}
1163 1180e4f0 Sjon Hortensius
1164 55eb9c44 --global
	/* Time to close LDAP connection */
1165 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1166 1180e4f0 Sjon Hortensius
1167 4de8f7ba Phil Davis
	$groups = print_r($memberof, true);
1168 1180e4f0 Sjon Hortensius
1169 55eb9c44 --global
	//log_error("Returning groups ".$groups." for user $username");
1170 1180e4f0 Sjon Hortensius
1171 55eb9c44 --global
	return $memberof;
1172
}
1173
1174 83e0d4c8 jim-p
function ldap_format_host($host) {
1175
	return is_ipaddrv6($host) ? "[$host]" : $host ;
1176
}
1177
1178 6306b5dd Ermal Lu?i
function ldap_backed($username, $passwd, $authcfg) {
1179 55eb9c44 --global
	global $debug, $config;
1180 1180e4f0 Sjon Hortensius
1181 1e0b1727 Phil Davis
	if (!$username) {
1182 55eb9c44 --global
		return;
1183 1e0b1727 Phil Davis
	}
1184 55eb9c44 --global
1185 1e0b1727 Phil Davis
	if (!function_exists("ldap_connect")) {
1186 55eb9c44 --global
		return;
1187 1e0b1727 Phil Davis
	}
1188 55eb9c44 --global
1189 1e0b1727 Phil Davis
	if (!isset($authcfg['ldap_nostrip_at']) && stristr($username, "@")) {
1190 2ce660ad smos
		$username_split = explode("@", $username);
1191 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1192 55eb9c44 --global
	}
1193 1e0b1727 Phil Davis
	if (stristr($username, "\\")) {
1194 cfbfd941 smos
		$username_split = explode("\\", $username);
1195 1180e4f0 Sjon Hortensius
		$username = $username_split[0];
1196 55eb9c44 --global
	}
1197
1198 c61e4626 Ermal Lu?i
	if ($authcfg) {
1199 1e0b1727 Phil Davis
		if (strstr($authcfg['ldap_urltype'], "Standard")) {
1200 c61e4626 Ermal Lu?i
			$ldapproto = "ldap";
1201 1e0b1727 Phil Davis
		} else {
1202 c61e4626 Ermal Lu?i
			$ldapproto = "ldaps";
1203 1e0b1727 Phil Davis
		}
1204
		$ldapserver = "{$ldapproto}://" . ldap_format_host($authcfg['host']);
1205
		$ldapport = $authcfg['ldap_port'];
1206
		if (!empty($ldapport)) {
1207 9f27de6d jim-p
			$ldapserver .= ":{$ldapport}";
1208 1e0b1727 Phil Davis
		}
1209
		$ldapbasedn = $authcfg['ldap_basedn'];
1210
		$ldapbindun = $authcfg['ldap_binddn'];
1211
		$ldapbindpw = $authcfg['ldap_bindpw'];
1212
		if (empty($ldapbindun) || empty($ldapbindpw)) {
1213 c61e4626 Ermal Lu?i
			$ldapanon = true;
1214 1e0b1727 Phil Davis
		} else {
1215 c61e4626 Ermal Lu?i
			$ldapanon = false;
1216 1e0b1727 Phil Davis
		}
1217
		$ldapauthcont = $authcfg['ldap_authcn'];
1218
		$ldapnameattribute = strtolower($authcfg['ldap_attr_user']);
1219
		$ldapextendedqueryenabled = $authcfg['ldap_extended_enabled'];
1220
		$ldapextendedquery = $authcfg['ldap_extended_query'];
1221
		$ldapfilter = "";
1222
		if (!$ldapextendedqueryenabled) {
1223
			$ldapfilter = "({$ldapnameattribute}={$username})";
1224
		} else {
1225
			$ldapfilter = "(&({$ldapnameattribute}={$username})({$ldapextendedquery}))";
1226
		}
1227
		$ldaptype = "";
1228
		$ldapver = $authcfg['ldap_protver'];
1229
		$ldapname = $authcfg['name'];
1230
		$ldapscope = $authcfg['ldap_scope'];
1231 d6b4dfe3 jim-p
		$ldaptimeout = is_numeric($authcfg['ldap_timeout']) ? $authcfg['ldap_timeout'] : 25;
1232 1e0b1727 Phil Davis
	} else {
1233 6306b5dd Ermal Lu?i
		return false;
1234 1e0b1727 Phil Davis
	}
1235 55eb9c44 --global
1236 1180e4f0 Sjon Hortensius
	/* first check if there is even an LDAP server populated */
1237 1e0b1727 Phil Davis
	if (!$ldapserver) {
1238 c61e4626 Ermal Lu?i
		if ($ldapfallback) {
1239 94021404 Carlos Eduardo Ramos
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined.  Defaulting to local user database. Visit System -> User Manager."));
1240 c61e4626 Ermal Lu?i
			return local_backed($username, $passwd);
1241 1e0b1727 Phil Davis
		} else {
1242 94021404 Carlos Eduardo Ramos
			log_error(gettext("ERROR! ldap_backed() called with no LDAP authentication server defined."));
1243 1e0b1727 Phil Davis
		}
1244 c61e4626 Ermal Lu?i
1245
		return false;
1246 55eb9c44 --global
	}
1247 1180e4f0 Sjon Hortensius
1248 1e0b1727 Phil Davis
	/* Setup CA environment if needed. */
1249
	ldap_setup_caenv($authcfg);
1250 fe2031ab Ermal
1251 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
1252 3d3081ec Andrew MacIsaac
	ldap_set_option($ldap, LDAP_OPT_DEREF, LDAP_DEREF_SEARCHING);
1253 906daddc Ermal
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, (int)$ldapver);
1254 d6b4dfe3 jim-p
	ldap_set_option($ldap, LDAP_OPT_TIMELIMIT, (int)$ldaptimeout);
1255
	ldap_set_option($ldap, LDAP_OPT_NETWORK_TIMEOUT, (int)$ldaptimeout);
1256 906daddc Ermal
1257 55eb9c44 --global
	/* Make sure we can connect to LDAP */
1258 c61e4626 Ermal Lu?i
	$error = false;
1259 1e0b1727 Phil Davis
	if (!($ldap = ldap_connect($ldapserver))) {
1260 c61e4626 Ermal Lu?i
		$error = true;
1261 1e0b1727 Phil Davis
	}
1262 c61e4626 Ermal Lu?i
1263
	if ($error == true) {
1264 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR!  Could not connect to server %s."), $ldapname));
1265 c61e4626 Ermal Lu?i
		return false;
1266 55eb9c44 --global
	}
1267 c61e4626 Ermal Lu?i
1268 55eb9c44 --global
	/* ok, its up.  now, lets bind as the bind user so we can search it */
1269 c61e4626 Ermal Lu?i
	$error = false;
1270 a5cd1c5a jim-p
	$ldapbindun = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindun) : $ldapbindun;
1271
	$ldapbindpw = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapbindpw) : $ldapbindpw;
1272 c61e4626 Ermal Lu?i
	if ($ldapanon == true) {
1273 1e0b1727 Phil Davis
		if (!($res = @ldap_bind($ldap))) {
1274
			$error = true;
1275
		}
1276
	} else if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
1277 c61e4626 Ermal Lu?i
		$error = true;
1278 1e0b1727 Phil Davis
	}
1279 c61e4626 Ermal Lu?i
1280
	if ($error == true) {
1281 6306b5dd Ermal Lu?i
		@ldap_close($ldap);
1282 94021404 Carlos Eduardo Ramos
		log_error(sprintf(gettext("ERROR! Could not bind to server %s."), $ldapname));
1283 c61e4626 Ermal Lu?i
		return false;
1284 55eb9c44 --global
	}
1285 1180e4f0 Sjon Hortensius
1286 55eb9c44 --global
	/* Get LDAP Authcontainers and split em up. */
1287 cfbfd941 smos
	$ldac_splits = explode(";", $ldapauthcont);
1288 1180e4f0 Sjon Hortensius
1289 086cf944 Phil Davis
	/* setup the usercount so we think we haven't found anyone yet */
1290 4de8f7ba Phil Davis
	$usercount = 0;
1291 55eb9c44 --global
1292
	/*****************************************************************/
1293 6990ad35 Phil Davis
	/*  We first find the user based on username and filter          */
1294
	/*  then, once we find the first occurrence of that person       */
1295
	/*  we set session variables to point to the OU and DN of the    */
1296
	/*  person.  To later be used by ldap_get_groups.                */
1297 55eb9c44 --global
	/*  that way we don't have to search twice.                      */
1298
	/*****************************************************************/
1299 1e0b1727 Phil Davis
	if ($debug) {
1300 3ac8324f Ermal
		log_auth(sprintf(gettext("Now Searching for %s in directory."), $username));
1301 1e0b1727 Phil Davis
	}
1302 c61e4626 Ermal Lu?i
	/* Iterate through the user containers for search */
1303
	foreach ($ldac_splits as $i => $ldac_split) {
1304 a5cd1c5a jim-p
		$ldac_split = isset($authcfg['ldap_utf8']) ? utf8_encode($ldac_split) : $ldac_split;
1305
		$ldapfilter = isset($authcfg['ldap_utf8']) ? utf8_encode($ldapfilter) : $ldapfilter;
1306
		$ldapsearchbasedn = isset($authcfg['ldap_utf8']) ? utf8_encode("{$ldac_split},{$ldapbasedn}") : "{$ldac_split},{$ldapbasedn}";
1307 c61e4626 Ermal Lu?i
		/* Make sure we just use the first user we find */
1308 1e0b1727 Phil Davis
		if ($debug) {
1309 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)));
1310 1e0b1727 Phil Davis
		}
1311
		if ($ldapscope == "one") {
1312 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_list";
1313 1e0b1727 Phil Davis
		} else {
1314 c61e4626 Ermal Lu?i
			$ldapfunc = "ldap_search";
1315 1e0b1727 Phil Davis
		}
1316 c61e4626 Ermal Lu?i
		/* Support legacy auth container specification. */
1317 1e0b1727 Phil Davis
		if (stristr($ldac_split, "DC=") || empty($ldapbasedn)) {
1318 6990ad35 Phil Davis
			$search = @$ldapfunc($ldap, $ldac_split, $ldapfilter);
1319 1e0b1727 Phil Davis
		} else {
1320 6990ad35 Phil Davis
			$search = @$ldapfunc($ldap, $ldapsearchbasedn, $ldapfilter);
1321 1e0b1727 Phil Davis
		}
1322 c61e4626 Ermal Lu?i
		if (!$search) {
1323 94021404 Carlos Eduardo Ramos
			log_error(sprintf(gettext("Search resulted in error: %s"), ldap_error($ldap)));
1324 c61e4626 Ermal Lu?i
			continue;
1325 55eb9c44 --global
		}
1326 4de8f7ba Phil Davis
		$info = ldap_get_entries($ldap, $search);
1327 c61e4626 Ermal Lu?i
		$matches = $info['count'];
1328 1e0b1727 Phil Davis
		if ($matches == 1) {
1329 c61e4626 Ermal Lu?i
			$userdn = $_SESSION['ldapdn'] = $info[0]['dn'];
1330
			$_SESSION['ldapou'] = $ldac_split[$i];
1331
			$_SESSION['ldapon'] = "true";
1332
			$usercount = 1;
1333
			break;
1334 55eb9c44 --global
		}
1335
	}
1336
1337 1e0b1727 Phil Davis
	if ($usercount != 1) {
1338 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1339 94021404 Carlos Eduardo Ramos
		log_error(gettext("ERROR! Either LDAP search failed, or multiple users were found."));
1340 1180e4f0 Sjon Hortensius
		return false;
1341 55eb9c44 --global
	}
1342 c61e4626 Ermal Lu?i
1343 55eb9c44 --global
	/* Now lets bind as the user we found */
1344 a5cd1c5a jim-p
	$passwd = isset($authcfg['ldap_utf8']) ? utf8_encode($passwd) : $passwd;
1345 c61e4626 Ermal Lu?i
	if (!($res = @ldap_bind($ldap, $userdn, $passwd))) {
1346 3697adb2 jim-p
		log_error(sprintf(gettext('ERROR! Could not login to server %1$s as user %2$s: %3$s'), $ldapname, $username, ldap_error($ldap)));
1347 6306b5dd Ermal Lu?i
		@ldap_unbind($ldap);
1348 c61e4626 Ermal Lu?i
		return false;
1349 55eb9c44 --global
	}
1350
1351 a5cd1c5a jim-p
	if ($debug) {
1352
		$userdn = isset($authcfg['ldap_utf8']) ? utf8_decode($userdn) : $userdn;
1353 2004def5 Ermal
		log_auth(sprintf(gettext('Logged in successfully as %1$s via LDAP server %2$s with DN = %3$s.'), $username, $ldapname, $userdn));
1354 a5cd1c5a jim-p
	}
1355 c61e4626 Ermal Lu?i
1356
	/* At this point we are bound to LDAP so the user was auth'd okay. Close connection. */
1357 6306b5dd Ermal Lu?i
	@ldap_unbind($ldap);
1358 55eb9c44 --global
1359
	return true;
1360
}
1361
1362 1492e02c Ermal
function radius_backed($username, $passwd, $authcfg, &$attributes = array()) {
1363 a13ce628 Ermal Lu?i
	global $debug, $config;
1364 55eb9c44 --global
	$ret = false;
1365
1366 868c6826 Ermal
	require_once("radius.inc");
1367
1368 55eb9c44 --global
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
1369 c61e4626 Ermal Lu?i
	if ($authcfg) {
1370
		$radiusservers = array();
1371
		$radiusservers[0]['ipaddr'] = $authcfg['host'];
1372
		$radiusservers[0]['port'] = $authcfg['radius_auth_port'];
1373
		$radiusservers[0]['sharedsecret'] = $authcfg['radius_secret'];
1374 bddd2be8 jim-p
		$radiusservers[0]['timeout'] = $authcfg['radius_timeout'];
1375 1e0b1727 Phil Davis
	} else {
1376 6306b5dd Ermal Lu?i
		return false;
1377 1e0b1727 Phil Davis
	}
1378 c61e4626 Ermal Lu?i
1379 1e0b1727 Phil Davis
	/* Add new servers to our instance */
1380 bddd2be8 jim-p
	foreach ($radiusservers as $radsrv) {
1381
		$timeout = (is_numeric($radsrv['timeout'])) ? $radsrv['timeout'] : 5;
1382
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret'], $timeout);
1383
	}
1384 55eb9c44 --global
1385 6e815096 Ermal
	if (PEAR::isError($rauth->start())) {
1386 55eb9c44 --global
		$retvalue['auth_val'] = 1;
1387
		$retvalue['error'] = $rauth->getError();
1388 1e0b1727 Phil Davis
		if ($debug) {
1389 7aaf60a8 k-paulius
			printf(gettext("RADIUS start: %s<br />\n"), $retvalue['error']);
1390 1e0b1727 Phil Davis
		}
1391 55eb9c44 --global
	}
1392
1393
	// XXX - billm - somewhere in here we need to handle securid challenge/response
1394
1395
	/* Send request */
1396
	$result = $rauth->send();
1397
	if (PEAR::isError($result)) {
1398
		$retvalue['auth_val'] = 1;
1399
		$retvalue['error'] = $result->getMessage();
1400 1e0b1727 Phil Davis
		if ($debug) {
1401 7aaf60a8 k-paulius
			printf(gettext("RADIUS send failed: %s<br />\n"), $retvalue['error']);
1402 1e0b1727 Phil Davis
		}
1403 55eb9c44 --global
	} else if ($result === true) {
1404 1e0b1727 Phil Davis
		if ($rauth->getAttributes()) {
1405 1492e02c Ermal
			$attributes = $rauth->listAttributes();
1406 1e0b1727 Phil Davis
		}
1407 55eb9c44 --global
		$retvalue['auth_val'] = 2;
1408 1e0b1727 Phil Davis
		if ($debug) {
1409 7aaf60a8 k-paulius
			printf(gettext("RADIUS Auth succeeded")."<br />\n");
1410 1e0b1727 Phil Davis
		}
1411 55eb9c44 --global
		$ret = true;
1412
	} else {
1413
		$retvalue['auth_val'] = 3;
1414 1e0b1727 Phil Davis
		if ($debug) {
1415 7aaf60a8 k-paulius
			printf(gettext("RADIUS Auth rejected")."<br />\n");
1416 1e0b1727 Phil Davis
		}
1417 55eb9c44 --global
	}
1418
1419
	// close OO RADIUS_AUTHENTICATION
1420
	$rauth->close();
1421
1422
	return $ret;
1423
}
1424
1425 c4a9f99a jim-p
/*
1426
	$attributes must contain a "class" key containing the groups and local
1427
	groups must exist to match.
1428
*/
1429
function radius_get_groups($attributes) {
1430
	$groups = array();
1431
	if (!empty($attributes) && is_array($attributes) && !empty($attributes['class'])) {
1432
		$groups = explode(";", $attributes['class']);
1433
		foreach ($groups as & $grp) {
1434 916fc1f8 jim-p
			$grp = trim($grp);
1435
			if (strtolower(substr($grp, 0, 3)) == "ou=") {
1436 c4a9f99a jim-p
				$grp = substr($grp, 3);
1437
			}
1438
		}
1439
	}
1440
	return $groups;
1441
}
1442
1443 7dd044f2 sullrich
function get_user_expiration_date($username) {
1444 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1445 1e0b1727 Phil Davis
	if ($user['expires']) {
1446 a13ce628 Ermal Lu?i
		return $user['expires'];
1447 1e0b1727 Phil Davis
	}
1448 a13ce628 Ermal Lu?i
}
1449
1450
function is_account_expired($username) {
1451
	$expirydate = get_user_expiration_date($username);
1452
	if ($expirydate) {
1453 4de8f7ba Phil Davis
		if (strtotime("-1 day") > strtotime(date("m/d/Y", strtotime($expirydate)))) {
1454 a13ce628 Ermal Lu?i
			return true;
1455 1e0b1727 Phil Davis
		}
1456 7dd044f2 sullrich
	}
1457 a13ce628 Ermal Lu?i
1458
	return false;
1459 7dd044f2 sullrich
}
1460
1461 b4bfd25d sullrich
function is_account_disabled($username) {
1462 a13ce628 Ermal Lu?i
	$user = getUserEntry($username);
1463 1e0b1727 Phil Davis
	if (isset($user['disabled'])) {
1464 a13ce628 Ermal Lu?i
		return true;
1465 1e0b1727 Phil Davis
	}
1466 a13ce628 Ermal Lu?i
1467 b4bfd25d sullrich
	return false;
1468
}
1469
1470 c61e4626 Ermal Lu?i
function auth_get_authserver($name) {
1471 1e0b1727 Phil Davis
	global $config;
1472
1473
	if (is_array($config['system']['authserver'])) {
1474
		foreach ($config['system']['authserver'] as $authcfg) {
1475
			if ($authcfg['name'] == $name) {
1476
				return $authcfg;
1477
			}
1478
		}
1479
	}
1480
	if ($name == "Local Database") {
1481 96568521 Vinicius Coque
		return array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1482 1e0b1727 Phil Davis
	}
1483 6306b5dd Ermal Lu?i
}
1484
1485
function auth_get_authserver_list() {
1486 1e0b1727 Phil Davis
	global $config;
1487 6306b5dd Ermal Lu?i
1488
	$list = array();
1489
1490 1e0b1727 Phil Davis
	if (is_array($config['system']['authserver'])) {
1491
		foreach ($config['system']['authserver'] as $authcfg) {
1492 6306b5dd Ermal Lu?i
			/* Add support for disabled entries? */
1493
			$list[$authcfg['name']] = $authcfg;
1494 1e0b1727 Phil Davis
		}
1495
	}
1496 6306b5dd Ermal Lu?i
1497 4de8f7ba Phil Davis
	$list["Local Database"] = array("name" => gettext("Local Database"), "type" => "Local Auth", "host" => $config['system']['hostname']);
1498 6306b5dd Ermal Lu?i
	return $list;
1499 c61e4626 Ermal Lu?i
}
1500
1501 c4a9f99a jim-p
function getUserGroups($username, $authcfg, &$attributes = array()) {
1502 fb0f22c0 Ermal Lu?i
	global $config;
1503
1504
	$allowed_groups = array();
1505
1506 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1507
		case 'ldap':
1508
			$allowed_groups = @ldap_get_groups($username, $authcfg);
1509
			break;
1510
		case 'radius':
1511 c4a9f99a jim-p
			$allowed_groups = @radius_get_groups($attributes);
1512 1e0b1727 Phil Davis
			break;
1513
		default:
1514
			$user = getUserEntry($username);
1515
			$allowed_groups = @local_user_get_groups($user, true);
1516
			break;
1517 fb0f22c0 Ermal Lu?i
	}
1518
1519
	$member_groups = array();
1520 1e0b1727 Phil Davis
	if (is_array($config['system']['group'])) {
1521
		foreach ($config['system']['group'] as $group) {
1522
			if (in_array($group['name'], $allowed_groups)) {
1523 fb0f22c0 Ermal Lu?i
				$member_groups[] = $group['name'];
1524 1e0b1727 Phil Davis
			}
1525
		}
1526 fb0f22c0 Ermal Lu?i
	}
1527
1528
	return $member_groups;
1529
}
1530
1531 1492e02c Ermal
function authenticate_user($username, $password, $authcfg = NULL, &$attributes = array()) {
1532 c61e4626 Ermal Lu?i
1533 b7369ff8 NewEraCracker
	if (is_array($username) || is_array($password)) {
1534
		return false;
1535
	}
1536
1537 c61e4626 Ermal Lu?i
	if (!$authcfg) {
1538
		return local_backed($username, $password);
1539
	}
1540
1541
	$authenticated = false;
1542 1e0b1727 Phil Davis
	switch ($authcfg['type']) {
1543
		case 'ldap':
1544
			if (ldap_backed($username, $password, $authcfg)) {
1545
				$authenticated = true;
1546
			}
1547
			break;
1548
		case 'radius':
1549
			if (radius_backed($username, $password, $authcfg, $attributes)) {
1550
				$authenticated = true;
1551
			}
1552
			break;
1553
		default:
1554
			/* lookup user object by name */
1555
			if (local_backed($username, $password)) {
1556
				$authenticated = true;
1557
			}
1558
			break;
1559
		}
1560 c61e4626 Ermal Lu?i
1561
	return $authenticated;
1562
}
1563
1564 6306b5dd Ermal Lu?i
function session_auth() {
1565 aa205c3b Ermal
	global $config, $_SESSION, $page;
1566 55eb9c44 --global
1567 49ddf9a1 Warren Baker
	// Handle HTTPS httponly and secure flags
1568 16789caa Renato Botelho
	$currentCookieParams = session_get_cookie_params();
1569
	session_set_cookie_params(
1570
		$currentCookieParams["lifetime"],
1571
		$currentCookieParams["path"],
1572
		NULL,
1573
		($config['system']['webgui']['protocol'] == "https"),
1574
		true
1575
	);
1576 49ddf9a1 Warren Baker
1577 1e0b1727 Phil Davis
	if (!session_id()) {
1578 9252d093 Ermal
		session_start();
1579 1e0b1727 Phil Davis
	}
1580 55eb9c44 --global
1581 dd030de9 Renato Botelho
	// Detect protocol change
1582 1e0b1727 Phil Davis
	if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
1583 dd030de9 Renato Botelho
		return false;
1584 1e0b1727 Phil Davis
	}
1585 dd030de9 Renato Botelho
1586 55eb9c44 --global
	/* Validate incoming login request */
1587 c4a9f99a jim-p
	$attributes = array();
1588 88165371 Ermal
	if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
1589 6306b5dd Ermal Lu?i
		$authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
1590 c4a9f99a jim-p
		if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg, $attributes) ||
1591 6306b5dd Ermal Lu?i
		    authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
1592 526f5b11 Renato Botelho
			// Generate a new id to avoid session fixation
1593 8588095f Renato Botelho
			session_regenerate_id();
1594 6306b5dd Ermal Lu?i
			$_SESSION['Logged_In'] = "True";
1595
			$_SESSION['Username'] = $_POST['usernamefld'];
1596 c4a9f99a jim-p
			$_SESSION['user_radius_attributes'] = $attributes;
1597 6306b5dd Ermal Lu?i
			$_SESSION['last_access'] = time();
1598 dd030de9 Renato Botelho
			$_SESSION['protocol'] = $config['system']['webgui']['protocol'];
1599 1e0b1727 Phil Davis
			if (!isset($config['system']['webgui']['quietlogin'])) {
1600 54bdff75 Vinicius Coque
				log_auth(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
1601 4fc3855f smos
			}
1602 1e0b1727 Phil Davis
			if (isset($_POST['postafterlogin'])) {
1603 92140621 Ermal
				return true;
1604 1e0b1727 Phil Davis
			} else {
1605
				if (empty($page)) {
1606 80b292f3 Ermal
					$page = "/";
1607 1e0b1727 Phil Davis
				}
1608 80b292f3 Ermal
				header("Location: {$page}");
1609
			}
1610 f23e6363 Ermal
			exit;
1611 a13ce628 Ermal Lu?i
		} else {
1612
			/* give the user an error message */
1613
			$_SESSION['Login_Error'] = "Username or Password incorrect";
1614 65f7fba8 Scott Ullrich
			log_auth("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
1615 1e0b1727 Phil Davis
			if (isAjax()) {
1616 a13ce628 Ermal Lu?i
				echo "showajaxmessage('{$_SESSION['Login_Error']}');";
1617
				return;
1618 55eb9c44 --global
			}
1619
		}
1620
	}
1621
1622
	/* Show login page if they aren't logged in */
1623 1e0b1727 Phil Davis
	if (empty($_SESSION['Logged_In'])) {
1624 55eb9c44 --global
		return false;
1625 1e0b1727 Phil Davis
	}
1626 55eb9c44 --global
1627
	/* If session timeout isn't set, we don't mark sessions stale */
1628 02647583 Ermal
	if (!isset($config['system']['webgui']['session_timeout'])) {
1629 bdadaf3c Chris Buechler
		/* Default to 4 hour timeout if one is not set */
1630
		if ($_SESSION['last_access'] < (time() - 14400)) {
1631
			$_GET['logout'] = true;
1632
			$_SESSION['Logout'] = true;
1633 1e0b1727 Phil Davis
		} else {
1634 1180e4f0 Sjon Hortensius
			$_SESSION['last_access'] = time();
1635 1e0b1727 Phil Davis
		}
1636 02647583 Ermal
	} else if (intval($config['system']['webgui']['session_timeout']) == 0) {
1637
		/* only update if it wasn't ajax */
1638 1e0b1727 Phil Davis
		if (!isAjax()) {
1639 02647583 Ermal
			$_SESSION['last_access'] = time();
1640 1e0b1727 Phil Davis
		}
1641 bdadaf3c Chris Buechler
	} else {
1642 55eb9c44 --global
		/* Check for stale session */
1643
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
1644
			$_GET['logout'] = true;
1645
			$_SESSION['Logout'] = true;
1646
		} else {
1647
			/* only update if it wasn't ajax */
1648 1e0b1727 Phil Davis
			if (!isAjax()) {
1649 55eb9c44 --global
				$_SESSION['last_access'] = time();
1650 1e0b1727 Phil Davis
			}
1651 55eb9c44 --global
		}
1652
	}
1653
1654
	/* user hit the logout button */
1655
	if (isset($_GET['logout'])) {
1656
1657 1e0b1727 Phil Davis
		if ($_SESSION['Logout']) {
1658 addc0439 Renato Botelho
			log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1659 1e0b1727 Phil Davis
		} else {
1660 addc0439 Renato Botelho
			log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
1661 1e0b1727 Phil Davis
		}
1662 55eb9c44 --global
1663
		/* wipe out $_SESSION */
1664
		$_SESSION = array();
1665
1666 1e0b1727 Phil Davis
		if (isset($_COOKIE[session_name()])) {
1667 55eb9c44 --global
			setcookie(session_name(), '', time()-42000, '/');
1668 1e0b1727 Phil Davis
		}
1669 55eb9c44 --global
1670
		/* and destroy it */
1671
		session_destroy();
1672
1673 cfbfd941 smos
		$scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
1674 55eb9c44 --global
		$scriptElms = count($scriptName);
1675
		$scriptName = $scriptName[$scriptElms-1];
1676
1677 1e0b1727 Phil Davis
		if (isAjax()) {
1678 55eb9c44 --global
			return false;
1679 1e0b1727 Phil Davis
		}
1680 55eb9c44 --global
1681
		/* redirect to page the user is on, it'll prompt them to login again */
1682 6f3d2063 Renato Botelho
		header("Location: {$scriptName}");
1683 55eb9c44 --global
1684
		return false;
1685
	}
1686
1687
	/*
1688
	 * this is for debugging purpose if you do not want to use Ajax
1689 1e0b1727 Phil Davis
	 * to submit a HTML form. It basically disables the observation
1690 55eb9c44 --global
	 * of the submit event and hence does not trigger Ajax.
1691
	 */
1692 1e0b1727 Phil Davis
	if ($_GET['disable_ajax']) {
1693 55eb9c44 --global
		$_SESSION['NO_AJAX'] = "True";
1694 1e0b1727 Phil Davis
	}
1695 55eb9c44 --global
1696
	/*
1697
	 * Same to re-enable Ajax.
1698
	 */
1699 1e0b1727 Phil Davis
	if ($_GET['enable_ajax']) {
1700 55eb9c44 --global
		unset($_SESSION['NO_AJAX']);
1701 1e0b1727 Phil Davis
	}
1702 55eb9c44 --global
1703
	return true;
1704
}
1705
1706 88165371 Ermal
?>