Project

General

Profile

Download (26.6 KB) Statistics
| Branch: | Tag: | Revision:
1 b0ed07d1 Scott Ullrich
<?php
2
/* $Id$ */
3
/*
4
		Copyright (C) 2007, 2008 Scott Ullrich <sullrich@gmail.com>
5
		All rights reserved.
6
7
        Copyright (C) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
8
        All rights reserved.
9
10
        Copyright (C) 2006 Paul Taylor <paultaylor@winn-dixie.com>.
11
        All rights reserved.
12
13
        Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
14
        All rights reserved.
15
16
        Redistribution and use in source and binary forms, with or without
17
        modification, are permitted provided that the following conditions are met:
18
19
        1. Redistributions of source code must retain the above copyright notice,
20
           this list of conditions and the following disclaimer.
21
22
        2. Redistributions in binary form must reproduce the above copyright
23
           notice, this list of conditions and the following disclaimer in the
24
           documentation and/or other materials provided with the distribution.
25
26
        THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
27
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
28
        AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29
        AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33
        CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34
        ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35
        POSSIBILITY OF SUCH DAMAGE.
36 6b07c15a Matthew Grooms
37
		DISABLE_PHP_LINT_CHECKING
38 b0ed07d1 Scott Ullrich
*/
39
40 651d4687 Matthew Grooms
/*
41
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
42
 * file courtesy of Michael Retterklieber.
43
 */
44
45 b0ed07d1 Scott Ullrich
require_once("functions.inc");
46 45ee90ed Matthew Grooms
47 b0ed07d1 Scott Ullrich
$groupindex = index_groups();
48
$userindex = index_users();
49
50 6b07c15a Matthew Grooms
function index_groups() {
51 269d6062 Scott Ullrich
	global $g, $debug, $config, $groupindex;
52 b0ed07d1 Scott Ullrich
53 6b07c15a Matthew Grooms
	$groupindex = array();
54 b0ed07d1 Scott Ullrich
55 6b07c15a Matthew Grooms
	if (isset($config['system']['group'])) {
56
		$i = 0;
57
		foreach($config['system']['group'] as $groupent) {
58
			$groupindex[$groupent['name']] = $i;
59
			$i++;
60 45ee90ed Matthew Grooms
		}
61
	}
62 925f3fe9 Matthew Grooms
63 6b07c15a Matthew Grooms
	return ($groupindex);
64 b0ed07d1 Scott Ullrich
}
65
66 6b07c15a Matthew Grooms
function index_users() {
67 269d6062 Scott Ullrich
	global $g, $debug, $config;
68 925f3fe9 Matthew Grooms
69 6b07c15a Matthew Grooms
	if (isset($config['system']['user'])) {
70
		$i = 0;
71
		foreach($config['system']['user'] as $userent) {
72
			$userindex[$userent['name']] = $i;
73
			$i++;
74
		}
75
	}
76
77
	return ($userindex);
78 b0ed07d1 Scott Ullrich
}
79
80 45ee90ed Matthew Grooms
function & getUserEntry($name) {
81 269d6062 Scott Ullrich
	global $debug, $config, $userindex;
82 6b07c15a Matthew Grooms
	if (isset($userindex[$name]))
83
		return $config['system']['user'][$userindex[$name]];
84 b0ed07d1 Scott Ullrich
}
85
86 6b07c15a Matthew Grooms
function & getUserEntryByUID($uid) {
87 269d6062 Scott Ullrich
	global $debug, $config;
88 6b07c15a Matthew Grooms
	foreach ($config['system']['user'] as & $user)
89
		if ($user['uid'] == $uid)
90
			return $user;
91 b0ed07d1 Scott Ullrich
92 6b07c15a Matthew Grooms
	return false;
93 b0ed07d1 Scott Ullrich
}
94
95 6b07c15a Matthew Grooms
function & getGroupEntry($name) {
96 269d6062 Scott Ullrich
	global $debug, $config, $groupindex;
97 6b07c15a Matthew Grooms
	if (isset($groupindex[$name]))
98
		return $config['system']['group'][$groupindex[$name]];
99 b0ed07d1 Scott Ullrich
}
100
101 613cf46c Matthew Grooms
function & getGroupEntryByGID($gid) {
102 269d6062 Scott Ullrich
	global $debug, $config;
103 613cf46c Matthew Grooms
	foreach ($config['system']['group'] as & $group)
104
		if ($group['gid'] == $gid)
105
			return $group;
106
107
	return false;
108
}
109
110 659fa7f2 Matthew Grooms
function local_backed($username, $passwd) {
111
112
	$user = getUserEntry($username);
113
	if (!$user)
114
		return false;
115
116
	$passwd = crypt($passwd, $user['password']);
117
118
	return ($passwd == $user['password']);
119
}
120
121
function local_sync_accounts() {
122 269d6062 Scott Ullrich
	global $debug, $config;
123 6f891c20 Scott Ullrich
	conf_mount_rw();
124 45ee90ed Matthew Grooms
125
	/* remove local users to avoid uid conflicts */
126 ce6af29a Matthew Grooms
	$fd = popen("/usr/sbin/pw usershow -a", "r");
127 45ee90ed Matthew Grooms
	if ($fd) {
128
		while (!feof($fd)) {
129
			$line = explode(":",fgets($fd));
130
			if (!strncmp($line[0], "_", 1))
131
				continue;
132
			if ($line[2] < 2000)
133
				continue;
134
			if ($line[2] > 65000)
135
				continue;
136 ce6af29a Matthew Grooms
			$cmd = "/usr/sbin/pw userdel {$line[2]}";
137 269d6062 Scott Ullrich
			if($debug)
138
				log_error("Running: {$cmd}");
139 ce6af29a Matthew Grooms
			mwexec($cmd);
140 45ee90ed Matthew Grooms
		}
141
		pclose($fd);
142
	}
143 b0ed07d1 Scott Ullrich
144 45ee90ed Matthew Grooms
	/* remove local groups to avoid gid conflicts */
145
	$gids = array();
146 ce6af29a Matthew Grooms
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
147 45ee90ed Matthew Grooms
	if ($fd) {
148
		while (!feof($fd)) {
149
			$line = explode(":",fgets($fd));
150
			if (!strncmp($line[0], "_", 1))
151
				continue;
152
			if ($line[2] < 2000)
153
				continue;
154
			if ($line[2] > 65000)
155
				continue;
156 ce6af29a Matthew Grooms
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
157 269d6062 Scott Ullrich
			if($debug)
158
				log_error("Running: {$cmd}");
159 ce6af29a Matthew Grooms
			mwexec($cmd);
160 45ee90ed Matthew Grooms
		}
161
		pclose($fd);
162
	}
163 b0ed07d1 Scott Ullrich
164 613cf46c Matthew Grooms
	/* make sure the all group exists */
165
	$allgrp = getGroupEntryByGID(1998);
166 659fa7f2 Matthew Grooms
	local_group_set($allgrp, true);
167 613cf46c Matthew Grooms
168 45ee90ed Matthew Grooms
	/* sync all local users */
169
	if (is_array($config['system']['user']))
170
		foreach ($config['system']['user'] as $user)
171 659fa7f2 Matthew Grooms
			local_user_set($user);
172 b0ed07d1 Scott Ullrich
173 45ee90ed Matthew Grooms
	/* sync all local groups */
174
	if (is_array($config['system']['group']))
175
		foreach ($config['system']['group'] as $group)
176 659fa7f2 Matthew Grooms
			local_group_set($group);
177 6f891c20 Scott Ullrich
178
	conf_mount_ro();
179
180 b0ed07d1 Scott Ullrich
}
181
182 659fa7f2 Matthew Grooms
function local_user_set(& $user) {
183 269d6062 Scott Ullrich
	global $g, $debug;
184 b0ed07d1 Scott Ullrich
185 1215fbb6 Scott Ullrich
	$home_base = "/home/";
186
	
187 d8721881 Scott Ullrich
	if (!is_dir($home_base)) 
188 45ee90ed Matthew Grooms
		mkdir($home_base, 0755);
189 d8721881 Scott Ullrich
	
190 45ee90ed Matthew Grooms
	$user_uid = $user['uid'];
191
	$user_name = $user['name'];
192
	$user_home = "{$home_base}/$user_name";
193
	$user_shell = "/etc/rc.initial";
194
	$user_group = "nobody";
195 b0ed07d1 Scott Ullrich
196 45ee90ed Matthew Grooms
	/* configure shell type */
197 fb1266d3 Matthew Grooms
	if (!userHasPrivilege($user, "user-shell-access")) {
198
		if (!userHasPrivilege($user, "user-copy-files"))
199 45ee90ed Matthew Grooms
			$user_shell = "/sbin/nologin";
200
		else
201
			$user_shell = "/usr/local/bin/scponly";
202
	}
203 b0ed07d1 Scott Ullrich
204 45ee90ed Matthew Grooms
	/* root user special handling */
205
	if ($user_uid == 0) {
206 ce6af29a Matthew Grooms
		$cmd = "/usr/sbin/pw usermod -n root -s /bin/sh -H 0";
207 269d6062 Scott Ullrich
		if($debug)
208
			log_error("Running: {$cmd}");
209 ce6af29a Matthew Grooms
		$fd = popen($cmd, "w");
210 45ee90ed Matthew Grooms
		fwrite($fd, $user['password']);
211
		pclose($fd);
212
		$user_group = "wheel";
213
	}
214 b0ed07d1 Scott Ullrich
215 45ee90ed Matthew Grooms
	/* read from pw db */
216
	$fd = popen("/usr/sbin/pw usershow {$user_name} 2>&1", "r");
217
	$pwread = fgets($fd);
218
	pclose($fd);
219
220
	/* determine add or mod */
221
	if (!strncmp($pwread, "pw:", 3))
222
		$user_op = "useradd";
223
	else
224
		$user_op = "usermod";
225
226
	/* add or mod pw db */
227
	$cmd = "/usr/sbin/pw {$user_op} -u {$user_uid} -n {$user_name}".
228
			" -g {$user_group} -G all -s {$user_shell} -d {$user_home}".
229 ce6af29a Matthew Grooms
			" -c ".escapeshellarg($user['fullname'])." -H 0 2>&1";
230 45ee90ed Matthew Grooms
231 269d6062 Scott Ullrich
	if($debug)
232
		log_error("Running: {$cmd}");
233 7fbca3f7 Ermal Luçi
	$fd = popen($cmd, "w");
234 45ee90ed Matthew Grooms
	fwrite($fd, $user['password']);
235
	pclose($fd);
236
237
	/* create user directory if required */
238 d8721881 Scott Ullrich
	if (!is_dir($user_home)) {
239 fb1266d3 Matthew Grooms
		mkdir($user_home, 0700);
240 1b02bfb7 Scott Ullrich
		exec("cp /root/.* {$home_base}/");
241 d8721881 Scott Ullrich
	}
242 45ee90ed Matthew Grooms
	chown($user_home, $user_name);
243
	chgrp($user_home, $user_group);
244
245 fb1266d3 Matthew Grooms
	/* write out ssh authorized key file */
246
	if($user['authorizedkeys']) {
247
		if (!is_dir("{$user_home}/.ssh"))
248
			mkdir("{$user_home}/.ssh", 0700);
249
		$keys = base64_decode($user['authorizedkeys']);
250
		file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
251
	}
252 b0ed07d1 Scott Ullrich
}
253
254 659fa7f2 Matthew Grooms
function local_user_del($user) {
255 8fe7e7c8 Scott Ullrich
	global $debug;
256 45ee90ed Matthew Grooms
	/* remove all memberships */
257 659fa7f2 Matthew Grooms
	local_user_get_groups($user);
258 45ee90ed Matthew Grooms
259
	/* delete from pw db */
260
	$cmd = "/usr/sbin/pw userdel {$user['name']}";
261 b0ed07d1 Scott Ullrich
262 269d6062 Scott Ullrich
	if($debug)
263
		log_error("Running: {$cmd}");
264 45ee90ed Matthew Grooms
	$fd = popen($cmd, "w");
265
	fwrite($fd, $user['password']);
266
	pclose($fd);
267 b0ed07d1 Scott Ullrich
}
268
269 659fa7f2 Matthew Grooms
function local_user_set_password(& $user, $password) {
270 6f891c20 Scott Ullrich
271 659fa7f2 Matthew Grooms
	$user['password'] = crypt($password);
272
	$user['md5-hash'] = md5($password);
273
274
	// Converts ascii to unicode.
275
	$astr = (string) $password;
276
	$ustr = '';
277
	for ($i = 0; $i < strlen($astr); $i++) {
278
		$a = ord($astr{$i}) << 8;
279
		$ustr.= sprintf("%X", $a);
280
	}
281
282
	// Generate the NT-HASH from the unicode string
283
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
284
}
285
286
function local_user_get_groups($user, $all = false) {
287 269d6062 Scott Ullrich
	global $debug, $config;
288 b0ed07d1 Scott Ullrich
289 45ee90ed Matthew Grooms
	$groups = array();
290
	if (!is_array($config['system']['group']))
291
		return $groups;
292 b0ed07d1 Scott Ullrich
293 45ee90ed Matthew Grooms
	foreach ($config['system']['group'] as $group)
294
		if ( $all || ( !$all && ($group['name'] != "all")))
295
			if (is_array($group['member']))
296
				if (in_array($user['uid'], $group['member']))
297
					$groups[] = $group['name'];
298 b0ed07d1 Scott Ullrich
299 45ee90ed Matthew Grooms
	sort($groups);
300 b0ed07d1 Scott Ullrich
301 45ee90ed Matthew Grooms
	return $groups;
302 0c49a2c3 Scott Ullrich
	
303 b0ed07d1 Scott Ullrich
}
304
305 659fa7f2 Matthew Grooms
function local_user_set_groups($user, $new_groups = NULL ) {
306 269d6062 Scott Ullrich
	global $debug, $config, $groupindex;
307 b0ed07d1 Scott Ullrich
308 45ee90ed Matthew Grooms
	if (!is_array($config['system']['group']))
309
		return;
310 b0ed07d1 Scott Ullrich
311 659fa7f2 Matthew Grooms
	$cur_groups = local_user_get_groups($user);
312 45ee90ed Matthew Grooms
	$mod_groups = array();
313 925f3fe9 Matthew Grooms
314 45ee90ed Matthew Grooms
	if (!is_array($new_groups))
315
		$new_groups = array();
316 b0ed07d1 Scott Ullrich
317 45ee90ed Matthew Grooms
	if (!is_array($cur_groups))
318
		$cur_groups = array();
319 b0ed07d1 Scott Ullrich
320 45ee90ed Matthew Grooms
	/* determine which memberships to add */
321
	foreach ($new_groups as $groupname) {
322
		if (in_array($groupname,$cur_groups))
323
			continue;
324
		$group = & $config['system']['group'][$groupindex[$groupname]];
325
		$group['member'][] = $user['uid'];
326
		$mod_groups[] = $group;
327
	}
328 b0ed07d1 Scott Ullrich
329 45ee90ed Matthew Grooms
	/* determine which memberships to remove */
330
	foreach ($cur_groups as $groupname) {
331
		if (in_array($groupname,$new_groups))
332
		continue;
333
		$group = & $config['system']['group'][$groupindex[$groupname]];
334
		$index = array_search($user['uid'], $group['member']);
335
		array_splice($group['member'], $index, 1);
336
		$mod_groups[] = $group;
337
	}
338 b0ed07d1 Scott Ullrich
339 45ee90ed Matthew Grooms
	/* sync all modified groups */
340
	foreach ($mod_groups as $group)
341 659fa7f2 Matthew Grooms
		local_group_set($group);
342 45ee90ed Matthew Grooms
}
343 b0ed07d1 Scott Ullrich
344 659fa7f2 Matthew Grooms
function local_group_set($group, $reset = false) {
345 8fe7e7c8 Scott Ullrich
	global $debug;
346 f01961a9 Scott Ullrich
347 45ee90ed Matthew Grooms
	$group_name = $group['name'];
348
	$group_gid = $group['gid'];
349
	$group_members = "''";
350 5878ca47 Matthew Grooms
	if (!$reset && count($group['member']))
351 45ee90ed Matthew Grooms
		$group_members = implode(",",$group['member']);
352 b0ed07d1 Scott Ullrich
353 45ee90ed Matthew Grooms
	/* read from group db */
354
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
355
	$pwread = fgets($fd);
356
	pclose($fd);
357 b0ed07d1 Scott Ullrich
358 45ee90ed Matthew Grooms
	/* determine add or mod */
359
	if (!strncmp($pwread, "pw:", 3))
360
		$group_op = "groupadd";
361
	else
362
		$group_op = "groupmod";
363 b0ed07d1 Scott Ullrich
364 45ee90ed Matthew Grooms
	/* add or mod group db */
365 ce6af29a Matthew Grooms
	$cmd = "/usr/sbin/pw {$group_op} {$group_name} -g {$group_gid} -M {$group_members} 2>&1";
366 b0ed07d1 Scott Ullrich
367 269d6062 Scott Ullrich
	if($debug)
368
		log_error("Running: {$cmd}");
369 a7db7d3a Ermal Lu?i
	$fd = popen($cmd, "w");
370 45ee90ed Matthew Grooms
	fwrite($fd, $user['password']);
371
	pclose($fd);
372 f01961a9 Scott Ullrich
373 b0ed07d1 Scott Ullrich
}
374
375 659fa7f2 Matthew Grooms
function local_group_del($group) {
376 8fe7e7c8 Scott Ullrich
	global $debug;
377 f01961a9 Scott Ullrich
378 45ee90ed Matthew Grooms
	/* delete from group db */
379
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
380 b0ed07d1 Scott Ullrich
381 269d6062 Scott Ullrich
	if($debug)
382
		log_error("Running: {$cmd}");
383 45ee90ed Matthew Grooms
	$fd = popen($cmd, "w");
384
	fwrite($fd, $user['password']);
385
	pclose($fd);
386 f01961a9 Scott Ullrich
387 b0ed07d1 Scott Ullrich
}
388
389
function ldap_test_connection() {
390 269d6062 Scott Ullrich
	global $debug, $config, $g;
391 b0ed07d1 Scott Ullrich
392
	$ldapserver = $config['system']['webgui']['ldapserver'];
393
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
394
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
395 925f3fe9 Matthew Grooms
396
	if (!($ldap = ldap_connect($ldapserver)))
397 b0ed07d1 Scott Ullrich
		return false;
398
399
	return true;
400
}
401
402
function ldap_test_bind() {
403 269d6062 Scott Ullrich
	global $debug, $config, $g;
404 b0ed07d1 Scott Ullrich
405 925f3fe9 Matthew Grooms
	$ldapserver = $config['system']['webgui']['ldapserver'];
406
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
407
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
408 a720f012 Scott Ullrich
    
409 925f3fe9 Matthew Grooms
	if (!($ldap = ldap_connect($ldapserver)))
410 b0ed07d1 Scott Ullrich
		return false;
411
412 925f3fe9 Matthew Grooms
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
413
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
414 a720f012 Scott Ullrich
    
415 925f3fe9 Matthew Grooms
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw)))
416 b0ed07d1 Scott Ullrich
		return false;
417
418
	return true;
419
}
420
421 a720f012 Scott Ullrich
function ldap_get_user_ous($show_complete_ou=true) {
422 269d6062 Scott Ullrich
	global $debug, $config, $g;
423 b0ed07d1 Scott Ullrich
424
	if(!function_exists("ldap_connect"))
425
		return;
426
427 925f3fe9 Matthew Grooms
	$ldapserver     = $config['system']['webgui']['ldapserver'];
428
	$ldapbindun     = $config['system']['webgui']['ldapbindun'];
429
	$ldapbindpw     = $config['system']['webgui']['ldapbindpw'];
430
	$ldapsearchbase = "{$config['system']['webgui']['ldapsearchbase']}";
431
	$ldaptype       = $config['system']['webgui']['backend'];
432 b0ed07d1 Scott Ullrich
433 925f3fe9 Matthew Grooms
	$ldapfilter = "(ou=*)";
434
	putenv('LDAPTLS_REQCERT=never');
435
	if (!($ldap = ldap_connect($ldapserver))) {
436 659fa7f2 Matthew Grooms
		log_error("ERROR!  ldap_get_groups() could not connect to server {$ldapserver}.  Defaulting to built-in local_backed()");
437
		$status = local_backed($username, $passwd);
438 925f3fe9 Matthew Grooms
		return $status;
439
	}
440 b0ed07d1 Scott Ullrich
441 925f3fe9 Matthew Grooms
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
442
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
443 b0ed07d1 Scott Ullrich
444 925f3fe9 Matthew Grooms
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
445 659fa7f2 Matthew Grooms
		log_error("ERROR! ldap_get_groups() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
446
		$status = local_backed($username, $passwd);
447 925f3fe9 Matthew Grooms
		return $status;
448
	}
449 b0ed07d1 Scott Ullrich
450 925f3fe9 Matthew Grooms
	$search = ldap_search($ldap, $ldapsearchbase, $ldapfilter);
451 b0ed07d1 Scott Ullrich
452 925f3fe9 Matthew Grooms
	$info = ldap_get_entries($ldap, $search);
453 b0ed07d1 Scott Ullrich
454
	$ous = array();
455
456 925f3fe9 Matthew Grooms
	if (is_array($info)) {
457
		foreach ($info as $inf) {
458
			if (!$show_complete_ou) {
459
				$inf_split = split(",", $inf['dn']);
460
				$ou = $inf_split[0];
461
				$ou = str_replace("OU=","", $ou);
462
			} else
463 b0ed07d1 Scott Ullrich
				if($inf['dn'])
464
					$ou = $inf['dn'];
465
			if($ou)
466
				$ous[] = $ou;
467 925f3fe9 Matthew Grooms
		}
468 b0ed07d1 Scott Ullrich
	}
469 925f3fe9 Matthew Grooms
470 01764862 Scott Ullrich
	//Tack on the default Users container for AD since its non-standard
471 925f3fe9 Matthew Grooms
	if($ldaptype == 'ldap')
472
		$ous[] = "CN=Users,".$ldapsearchbase;
473 01764862 Scott Ullrich
474 b0ed07d1 Scott Ullrich
	return $ous;
475
}
476
477
function ldap_get_groups($username) {
478 269d6062 Scott Ullrich
	global $debug, $config;
479 b0ed07d1 Scott Ullrich
	
480
	if(!function_exists("ldap_connect"))
481
		return;
482
	
483
	if(!$username) 
484
		return false;
485
486
	if(stristr($username, "@")) {
487
		$username_split=split("\@", $username);
488
		$username = $username_split[0];		
489
	}
490 925f3fe9 Matthew Grooms
491
	if(stristr($username, "\\")) {
492
		$username_split=split("\\", $username);
493
		$username = $username_split[0];        
494
	}    
495 b0ed07d1 Scott Ullrich
	
496 01764862 Scott Ullrich
	//log_error("Getting LDAP groups for {$username}.");
497 b0ed07d1 Scott Ullrich
	
498 4989bc66 Scott Ullrich
	$ldapserver         = $config['system']['webgui']['ldapserver'];
499
	$ldapbindun         = $config['system']['webgui']['ldapbindun'];
500
	$ldapbindpw         = $config['system']['webgui']['ldapbindpw'];
501
	$ldapfilter         = $config['system']['webgui']['ldapfilter'];
502
	$ldapfilter         = str_replace("\$username", $username, $ldapfilter);
503 b0ed07d1 Scott Ullrich
	$ldapgroupattribute = $config['system']['webgui']['ldapgroupattribute'];
504 4989bc66 Scott Ullrich
	$ldapdn             = $_SESSION['ldapdn'];
505
	 
506 925f3fe9 Matthew Grooms
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
507
	$ldapgroupattribute = strtolower($ldapgroupattribute);
508 b0ed07d1 Scott Ullrich
509 4989bc66 Scott Ullrich
	/* connect and see if server is up */
510 01764862 Scott Ullrich
	putenv('LDAPTLS_REQCERT=never');
511 b0ed07d1 Scott Ullrich
	if (!($ldap = ldap_connect($ldapserver))) {
512 659fa7f2 Matthew Grooms
		log_error("ERROR!  ldap_get_groups() could not connect to server {$ldapserver}.  Defaulting to built-in local_backed()");
513
		$status = local_backed($username, $passwd);
514 b0ed07d1 Scott Ullrich
		return $status;	
515
	}
516 4989bc66 Scott Ullrich
    
517 925f3fe9 Matthew Grooms
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
518
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
519 b0ed07d1 Scott Ullrich
520 4989bc66 Scott Ullrich
	/* bind as user that has rights to read group attributes */
521 b0ed07d1 Scott Ullrich
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
522 659fa7f2 Matthew Grooms
		log_error("ERROR! ldap_get_groups() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
523
		$status = local_backed($username, $passwd);
524 b0ed07d1 Scott Ullrich
		return $status;
525
	}
526
527 4989bc66 Scott Ullrich
	/* get groups from DN found */
528
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
529
	/* since we know the DN is in $_SESSION['ldapdn'] */
530 01764862 Scott Ullrich
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
531
	$search    = ldap_read($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
532 925f3fe9 Matthew Grooms
	$info      = ldap_get_entries($ldap, $search);
533 b0ed07d1 Scott Ullrich
534 925f3fe9 Matthew Grooms
	$countem = $info["count"];	
535
	$memberof = array();
536 b0ed07d1 Scott Ullrich
	
537
	if(is_array($info[0][$ldapgroupattribute])) {
538 925f3fe9 Matthew Grooms
		/* Iterate through the groups and throw them into an array */
539
		foreach ($info[0][$ldapgroupattribute] as $member) {
540
			if (stristr($member, "CN=") !== false) {
541
				$membersplit = split(",", $member);
542
				$memberof[] = preg_replace("/CN=/i", "", $membersplit[0]);
543
			}
544
		}
545 b0ed07d1 Scott Ullrich
	}
546
	
547
	/* Time to close LDAP connection */
548
	ldap_close($ldap);
549
	
550
	$groups = print_r($memberof,true);
551
	
552 925f3fe9 Matthew Grooms
	//log_error("Returning groups ".$groups." for user $username");
553 b0ed07d1 Scott Ullrich
	
554
	return $memberof;
555
}
556
557
function ldap_backed($username, $passwd) {
558 269d6062 Scott Ullrich
	global $debug, $config;
559 b0ed07d1 Scott Ullrich
	
560
	if(!$username) 
561
		return;
562
563
	if(!function_exists("ldap_connect"))
564
		return;
565 925f3fe9 Matthew Grooms
566
	$adbindas = $username;
567 4989bc66 Scott Ullrich
    
568 925f3fe9 Matthew Grooms
	if(stristr($username, "@")) {
569
		$username_split=split("\@", $username);
570
		$username = $username_split[0];        
571
	}
572
	if(stristr($username, "\\")) {
573
		$username_split=split("\\", $username);
574
		$username = $username_split[0];        
575
	}
576
577 4989bc66 Scott Ullrich
	$ldapserver         = $config['system']['webgui']['ldapserver'];
578
	$ldapbindun         = $config['system']['webgui']['ldapbindun'];
579
	$ldapbindpw         = $config['system']['webgui']['ldapbindpw'];
580 925f3fe9 Matthew Grooms
	$ldapauthcont       = $config['system']['webgui']['ldapauthcontainers'];   
581
	$ldapnameattribute  = $config['system']['webgui']['ldapnameattribute'];  
582
	$ldapfilter         = $config['system']['webgui']['ldapfilter'];
583
	$ldaptype           = $config['system']['webgui']['backend'];
584
	$ldapfilter = str_replace("\$username", $username, $ldapfilter);
585
586
	/* first check if there is even an LDAP server populated */ 
587
	if(!$ldapserver) {
588 659fa7f2 Matthew Grooms
		log_error("ERROR!  ldap_backed() backed selected with no LDAP authentication server defined.  Defaulting to built-in local_backed().     Visit System -> User Manager -> Settings.");
589
		$status = local_backed($username, $passwd);
590 b0ed07d1 Scott Ullrich
		return $status;
591
	}
592
	
593 4989bc66 Scott Ullrich
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
594 925f3fe9 Matthew Grooms
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
595 4989bc66 Scott Ullrich
596
	/* Make sure we can connect to LDAP */
597 01764862 Scott Ullrich
	putenv('LDAPTLS_REQCERT=never');
598 b0ed07d1 Scott Ullrich
	if (!($ldap = ldap_connect($ldapserver))) {
599 659fa7f2 Matthew Grooms
		log_error("ERROR!  ldap_backed() could not connect to server {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed().     Visit System -> User Manager -> Settings.");
600
		$status = local_backed($username, $passwd);		
601 b0ed07d1 Scott Ullrich
		return $status;	
602
	}
603 4989bc66 Scott Ullrich
	/* ok, its up.  now, lets bind as the bind user so we can search it */
604
	if (!($res = ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
605 659fa7f2 Matthew Grooms
		log_error("ERROR! ldap_backed() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
606 925f3fe9 Matthew Grooms
		ldap_close($ldap);
607 659fa7f2 Matthew Grooms
		$status = local_backed($username, $passwd);
608 925f3fe9 Matthew Grooms
		return $status;
609 b0ed07d1 Scott Ullrich
	}
610 a720f012 Scott Ullrich
	
611
	/* Get LDAP Authcontainers and split em up. */
612 925f3fe9 Matthew Grooms
	$ldac_split = split(";", $ldapauthcont);
613 a720f012 Scott Ullrich
	
614
	/* now count how many there are */
615
	$containers = count($ldac_split);
616 01764862 Scott Ullrich
	log_error("Number of Authentication Containers to search for $username is {$containers}");
617 a720f012 Scott Ullrich
	
618
	/* setup the usercount so we think we havn't found anyone yet */
619 4989bc66 Scott Ullrich
	$usercount  = 0;
620 925f3fe9 Matthew Grooms
621
	/******************************/
622
	/* Currently LDAP Types are   */
623
	/* LDAP = Active Directory    */
624
	/* LDAPOTHER = eDir/Openldap  */
625
	/******************************/      
626 a720f012 Scott Ullrich
        
627 925f3fe9 Matthew Grooms
	/*****************************************************************/
628 4989bc66 Scott Ullrich
	/* Now Active Directory We keep this seperate for future addons. */
629 925f3fe9 Matthew Grooms
	/*****************************************************************/
630
	/* Now LDAP other.  eDirectory or Netscape or Sunone or OpenLDAP */
631
	/*****************************************************************/
632
	/*  We First find the user based on username and filter          */
633
	/*  Then, once we find the first occurance of that person        */
634
	/*  We set seesion variables to ponit to the OU and DN of the    */
635
	/*  Person.  To later be used by ldap_get_groups.                */
636
	/*  that way we don't have to search twice.                      */
637
	/*****************************************************************/
638 4989bc66 Scott Ullrich
	if ($ldaptype == 'ldap'){
639 925f3fe9 Matthew Grooms
		log_error("Now Searching for {$username} in Active directory.");
640
		/* Iterate through the user containers for search */
641
		for ($i=0;$i<$containers;$i++){
642
			/* Make sure we just use the first user we find */
643
			log_error("Now Searching in {$ldac_split[$i]} for {$ldapfilter}.");
644
			$search	 = ldap_search($ldap,$ldac_split[$i],$ldapfilter);
645
			$info	 = ldap_get_entries($ldap,$search);
646
			$matches = $info['count'];
647
			log_error("Matches Found = {$matches}");
648
			if ($matches == 1){
649
				$_SESSION['ldapdn'] = $info[0]['dn'];
650
				$_SESSION['ldapou'] = $ldac_split[$i];
651
				$_SESSION['ldapon'] = "true";
652
				$ldapdn = $_SESSION['ldapdn'];
653
				$userou = $_SESSION['ldapou'];
654
				break;
655
			}
656
		}
657 4989bc66 Scott Ullrich
658 925f3fe9 Matthew Grooms
		if ($matches == 1){
659
			$binduser = $adbindas;
660
			log_error("Going to login as {$username} - DN = {$_SESSION['ldapdn']}");
661
		}
662
		if ($matches != 1){
663
			log_error("ERROR! Either LDAP search failed, or multiple users were found");
664 659fa7f2 Matthew Grooms
			$status = local_backed($username, $passwd);
665 925f3fe9 Matthew Grooms
			$_SESSION['ldapon'] = "false";
666
			ldap_close($ldap);
667
			return $status;                         
668
		}
669
	}
670
671
	/*****************************************************************/
672
	/* Now LDAP other.  eDirectory or Netscape or Sunone or OpenLDAP */
673
	/*****************************************************************/
674
	/*  We First find the user based on username and filter          */
675
	/*  Then, once we find the first occurance of that person        */
676
	/*  We set seesion variables to ponit to the OU and DN of the    */
677
	/*  Person.  To later be used by ldap_get_groups.                */
678
	/*  that way we don't have to search twice.                      */
679
	/*****************************************************************/
680 4989bc66 Scott Ullrich
	if ($ldaptype == 'ldapother'){
681 925f3fe9 Matthew Grooms
		log_error("Now Searching for {$username} in LDAP.");
682
		/* Iterate through the user containers for search */
683
		for ($i=0;$i<$containers;$i++){
684
			/* Make sure we just use the first user we find */
685
			log_error("Now searching in {$ldac_split[$i]} for {$ldapfilter}.");
686
			$search  = ldap_search($ldap,$ldac_split[$i],$ldapfilter);
687
            $info    = ldap_get_entries($ldap,$search);
688
            $matches = $info['count'];
689
            log_error("Matches Found = {$matches}.");
690 4989bc66 Scott Ullrich
                                      
691 925f3fe9 Matthew Grooms
			if ($matches == 1){
692
				$_SESSION['ldapdn'] = $info[0]['dn'];
693
				$_SESSION['ldapou'] = $ldac_split[$i];
694
				$_SESSION['ldapon'] = "true";
695
				$ldapdn = $_SESSION['ldapdn'];
696
				$userou = $_SESSION['ldapou'];
697
				break;
698
			}
699
		}
700
		if($matches == 1){
701
			$binduser = $ldapnameattribute."=".$username.",".$userou;
702
			log_error("Going to login as {$username} - DN = {$_SESSION['ldapdn']}");
703
		}
704
		if($matches != 1){
705
			log_error("ERROR! Either LDAP search failed, or multiple users were found");
706 659fa7f2 Matthew Grooms
			$status = local_backed($username, $passwd);
707 925f3fe9 Matthew Grooms
			ldap_close($ldap);
708
			$_SESSION['ldapon'] = "false";
709
			return $status;                         
710
		}
711 4989bc66 Scott Ullrich
	}
712 a720f012 Scott Ullrich
	
713 925f3fe9 Matthew Grooms
	/* Now lets bind as the user we found */
714
	if (!($res = @ldap_bind($ldap, $binduser, $passwd))) {
715 659fa7f2 Matthew Grooms
		log_error("ERROR!  ldap_backed() could not bind to {$ldapserver} - {$username} - {$passwd}.  Defaulting to built-in local_backed().    Visit System -> User Manager -> Settings.");
716
		$status = local_backed($username, $passwd);
717 925f3fe9 Matthew Grooms
		return $status;
718
	}
719 a720f012 Scott Ullrich
720 01764862 Scott Ullrich
	log_error("$binduser succesfully logged in via LDAP.");
721 925f3fe9 Matthew Grooms
722 a720f012 Scott Ullrich
	/* At this point we are bound to LDAP so the user was auth'd okay. */
723 b0ed07d1 Scott Ullrich
	return true;
724
}
725
726
function radius_backed($username, $passwd){
727 269d6062 Scott Ullrich
	global $debug, $config, $debug;
728 925f3fe9 Matthew Grooms
	$ret = false;
729
	$radiusservers = $config['system']['radius']['servers'];
730
731
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
732
	/* Add a new servers to our instance */
733
	foreach ($radiusservers as $radsrv)
734
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
735
736
	if (!$rauth->start()) {
737
		$retvalue['auth_val'] = 1;
738
		$retvalue['error'] = $rauth->getError();
739
		if ($debug)
740
			printf("Radius start: %s<br>\n", $retvalue['error']);
741
	}
742 b0ed07d1 Scott Ullrich
743 925f3fe9 Matthew Grooms
	// XXX - billm - somewhere in here we need to handle securid challenge/response
744
745
	/* Send request */
746
	$result = $rauth->send();
747
	if (PEAR::isError($result)) {
748
		$retvalue['auth_val'] = 1;
749
		$retvalue['error'] = $result->getMessage();
750
		if ($debug)
751
			printf("Radius send failed: %s<br>\n", $retvalue['error']);
752
	} else if ($result === true) {
753
		$retvalue['auth_val'] = 2;
754
		if ($debug)
755
			printf(gettext("Radius Auth succeeded")."<br>\n");
756
		$ret = true;
757
	} else {
758
		$retvalue['auth_val'] = 3;
759
		if ($debug)
760
			printf(gettext("Radius Auth rejected")."<br>\n");
761
	}
762
763
	// close OO RADIUS_AUTHENTICATION
764
	$rauth->close();
765
766
	return $ret;
767
}
768 b0ed07d1 Scott Ullrich
769 659fa7f2 Matthew Grooms
function session_auth($backing) {
770 269d6062 Scott Ullrich
	global $g, $debug, $HTTP_SERVER_VARS, $userindex, $config;
771 659fa7f2 Matthew Grooms
772
	session_start();
773
774
	/* Validate incoming login request */
775
	if (isset($_POST['login'])) {
776
		if ($backing($_POST['usernamefld'], $_POST['passwordfld'])) {
777
			$_SESSION['Logged_In'] = "True";
778
			$_SESSION['Username'] = $_POST['usernamefld'];
779
			$_SESSION['last_access'] = time();
780
			log_error("Successful login for user '{$_POST['usernamefld']}' from: {$_SERVER['REMOTE_ADDR']}");
781
		} else {
782
			/* give the user a more detailed error message */
783
			if (isset($userindex[$_POST['usernamefld']])) {
784
				$_SESSION['Login_Error'] = "Username or Password incorrect";
785
				log_error("Wrong password entered for user '{$_POST['usernamefld']}' from: {$_SERVER['REMOTE_ADDR']}");
786
				if(isAjax()) {
787
					echo "showajaxmessage('{$_SESSION['Login_Error']}');";
788
					return;
789
				}
790
			} else {
791
				$_SESSION['Login_Error'] = "Username or Password incorrect";
792
				log_error("Attempted login for invalid user '{$_POST['usernamefld']}' from: {$_SERVER['REMOTE_ADDR']}");
793
				if(isAjax()) {
794
					echo "showajaxmessage('{$_SESSION['Login_Error']}');";
795
					return;
796
				}
797
			}
798
		}
799
	}
800
801
	/* Show login page if they aren't logged in */
802
	if (empty($_SESSION['Logged_In'])) {
803
		/* Don't display login forms to AJAX */
804
		if (isAjax())
805
			return false;
806
		require_once("authgui.inc");
807
		display_login_form();
808
		return false;
809
	}
810
811
	/* If session timeout isn't set, we don't mark sessions stale */
812
	if (!isset($config['system']['webgui']['session_timeout']) ||
813
		$config['system']['webgui']['session_timeout'] == 0 ||
814
		$config['system']['webgui']['session_timeout'] == "")
815
		$_SESSION['last_access'] = time();
816
	else {
817
		/* Check for stale session */
818
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
819
			$_GET['logout'] = true;
820
			$_SESSION['Logout'] = true;
821
		} else {
822
			/* only update if it wasn't ajax */
823
			if (!isAjax())
824
				$_SESSION['last_access'] = time();
825
		}
826
	}
827
828
	/* obtain user object */
829
	$user = getUserEntry($_SESSION['Username']);
830
831
	/* user hit the logout button */
832
	if (isset($_GET['logout'])) {
833
834
		if ($_SESSION['Logout'])
835
			log_error("Session timed out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
836
		else
837
			log_error("User logged out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
838
839
		/* wipe out $_SESSION */
840
		$_SESSION = array();
841
842
		if (isset($_COOKIE[session_name()]))
843
			setcookie(session_name(), '', time()-42000, '/');
844
845
		/* and destroy it */
846
		session_destroy();
847
848
		$scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
849
		$scriptElms = count($scriptName);
850
		$scriptName = $scriptName[$scriptElms-1];
851
852
		if (isAjax())
853
			return false;
854
855
		/* redirect to page the user is on, it'll prompt them to login again */
856
		pfSenseHeader($scriptName);
857
858
		return false;
859
	}
860
861
	/*
862
	 * this is for debugging purpose if you do not want to use Ajax
863
	 * to submit a HTML form. It basically diables the observation
864
	 * of the submit event and hence does not trigger Ajax.
865
	 */
866
	if ($_GET['disable_ajax']) {
867
		$_SESSION['NO_AJAX'] = "True";
868
		$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
869
		return true;
870
	}
871
872
	/*
873
	 * Same to re-enable Ajax.
874
	 */
875
	if ($_GET['enable_ajax']) {
876
		unset($_SESSION['NO_AJAX']);
877
		$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
878
		return true;
879
	}
880
881
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
882
	return true;
883
}
884
885 7fbca3f7 Ermal Luçi
?>