Project

General

Profile

Download (26.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?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

    
37
		DISABLE_PHP_LINT_CHECKING
38
*/
39

    
40
/*
41
 * NOTE : Portions of the mschapv2 support was based on the BSD licensed CHAP.php
42
 * file courtesy of Michael Retterklieber.
43
 */
44

    
45
require_once("functions.inc");
46

    
47
$groupindex = index_groups();
48
$userindex = index_users();
49

    
50
function index_groups() {
51
	global $g, $debug, $config, $groupindex;
52

    
53
	$groupindex = array();
54

    
55
	if (isset($config['system']['group'])) {
56
		$i = 0;
57
		foreach($config['system']['group'] as $groupent) {
58
			$groupindex[$groupent['name']] = $i;
59
			$i++;
60
		}
61
	}
62

    
63
	return ($groupindex);
64
}
65

    
66
function index_users() {
67
	global $g, $debug, $config;
68

    
69
	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
}
79

    
80
function & getUserEntry($name) {
81
	global $debug, $config, $userindex;
82
	if (isset($userindex[$name]))
83
		return $config['system']['user'][$userindex[$name]];
84
}
85

    
86
function & getUserEntryByUID($uid) {
87
	global $debug, $config;
88
	foreach ($config['system']['user'] as & $user)
89
		if ($user['uid'] == $uid)
90
			return $user;
91

    
92
	return false;
93
}
94

    
95
function & getGroupEntry($name) {
96
	global $debug, $config, $groupindex;
97
	if (isset($groupindex[$name]))
98
		return $config['system']['group'][$groupindex[$name]];
99
}
100

    
101
function & getGroupEntryByGID($gid) {
102
	global $debug, $config;
103
	foreach ($config['system']['group'] as & $group)
104
		if ($group['gid'] == $gid)
105
			return $group;
106

    
107
	return false;
108
}
109

    
110
function local_backed($username, $passwd) {
111

    
112
	$user = getUserEntry($username);
113
	if (!$user)
114
		return false;
115

    
116
	if ($user['password'])
117
	{
118
		$passwd = crypt($passwd, $user['password']);
119
		if ($passwd == $user['password'])
120
			return true;
121
	}
122

    
123
	if ($user['md5-hash'])
124
	{
125
		$passwd = md5($passwd);
126
		if ($passwd == $user['md5-hash'])
127
			return true;
128
	}
129

    
130
	return false;
131
}
132

    
133
function local_sync_accounts() {
134
	global $debug, $config;
135
	conf_mount_rw();
136

    
137
	/* remove local users to avoid uid conflicts */
138
	$fd = popen("/usr/sbin/pw usershow -a", "r");
139
	if ($fd) {
140
		while (!feof($fd)) {
141
			$line = explode(":",fgets($fd));
142
			if (!strncmp($line[0], "_", 1))
143
				continue;
144
			if ($line[2] < 2000)
145
				continue;
146
			if ($line[2] > 65000)
147
				continue;
148
			$cmd = "/usr/sbin/pw userdel {$line[2]}";
149
			if($debug)
150
				log_error("Running: {$cmd}");
151
			mwexec($cmd);
152
		}
153
		pclose($fd);
154
	}
155

    
156
	/* remove local groups to avoid gid conflicts */
157
	$gids = array();
158
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
159
	if ($fd) {
160
		while (!feof($fd)) {
161
			$line = explode(":",fgets($fd));
162
			if (!strncmp($line[0], "_", 1))
163
				continue;
164
			if ($line[2] < 2000)
165
				continue;
166
			if ($line[2] > 65000)
167
				continue;
168
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
169
			if($debug)
170
				log_error("Running: {$cmd}");
171
			mwexec($cmd);
172
		}
173
		pclose($fd);
174
	}
175

    
176
	/* make sure the all group exists */
177
	$allgrp = getGroupEntryByGID(1998);
178
	local_group_set($allgrp, true);
179

    
180
	/* sync all local users */
181
	if (is_array($config['system']['user']))
182
		foreach ($config['system']['user'] as $user)
183
			local_user_set($user);
184

    
185
	/* sync all local groups */
186
	if (is_array($config['system']['group']))
187
		foreach ($config['system']['group'] as $group)
188
			local_group_set($group);
189

    
190
	conf_mount_ro();
191

    
192
}
193

    
194
function local_user_set(& $user) {
195
	global $g, $debug;
196

    
197
	$home_base = "/home/";
198
	
199
	if (!is_dir($home_base)) 
200
		mkdir($home_base, 0755);
201
	
202
	$user_uid = $user['uid'];
203
	$user_name = $user['name'];
204
	$user_home = "{$home_base}/$user_name";
205
	$user_shell = "/etc/rc.initial";
206
	$user_group = "nobody";
207

    
208
	/* configure shell type */
209
	if (!userHasPrivilege($user, "user-shell-access")) {
210
		if (!userHasPrivilege($user, "user-copy-files"))
211
			$user_shell = "/sbin/nologin";
212
		else
213
			$user_shell = "/usr/local/bin/scponly";
214
	}
215

    
216
	/* root user special handling */
217
	if ($user_uid == 0) {
218
		$cmd = "/usr/sbin/pw usermod -n root -s /bin/sh -H 0";
219
		if($debug)
220
			log_error("Running: {$cmd}");
221
		$fd = popen($cmd, "w");
222
		fwrite($fd, $user['password']);
223
		pclose($fd);
224
		$user_group = "wheel";
225
	}
226

    
227
	/* read from pw db */
228
	$fd = popen("/usr/sbin/pw usershow {$user_name} 2>&1", "r");
229
	$pwread = fgets($fd);
230
	pclose($fd);
231

    
232
	/* determine add or mod */
233
	if (!strncmp($pwread, "pw:", 3))
234
		$user_op = "useradd";
235
	else
236
		$user_op = "usermod";
237

    
238
	/* add or mod pw db */
239
	$cmd = "/usr/sbin/pw {$user_op} -u {$user_uid} -n {$user_name}".
240
			" -g {$user_group} -G all -s {$user_shell} -d {$user_home}".
241
			" -c ".escapeshellarg($user['fullname'])." -H 0 2>&1";
242

    
243
	if($debug)
244
		log_error("Running: {$cmd}");
245
	$fd = popen($cmd, "w");
246
	fwrite($fd, $user['password']);
247
	pclose($fd);
248

    
249
	/* create user directory if required */
250
	if (!is_dir($user_home)) {
251
		mkdir($user_home, 0700);
252
		exec("cp /root/.* {$home_base}/");
253
	}
254
	chown($user_home, $user_name);
255
	chgrp($user_home, $user_group);
256

    
257
	/* write out ssh authorized key file */
258
	if($user['authorizedkeys']) {
259
		if (!is_dir("{$user_home}/.ssh"))
260
			mkdir("{$user_home}/.ssh", 0700);
261
		$keys = base64_decode($user['authorizedkeys']);
262
		file_put_contents("{$user_home}/.ssh/authorized_keys", $keys);
263
	}
264
}
265

    
266
function local_user_del($user) {
267
	global $debug;
268
	/* remove all memberships */
269
	local_user_get_groups($user);
270

    
271
	/* delete from pw db */
272
	$cmd = "/usr/sbin/pw userdel {$user['name']}";
273

    
274
	if($debug)
275
		log_error("Running: {$cmd}");
276
	$fd = popen($cmd, "w");
277
	fwrite($fd, $user['password']);
278
	pclose($fd);
279
}
280

    
281
function local_user_set_password(& $user, $password) {
282

    
283
	$user['password'] = crypt($password);
284
	$user['md5-hash'] = md5($password);
285

    
286
	// Converts ascii to unicode.
287
	$astr = (string) $password;
288
	$ustr = '';
289
	for ($i = 0; $i < strlen($astr); $i++) {
290
		$a = ord($astr{$i}) << 8;
291
		$ustr.= sprintf("%X", $a);
292
	}
293

    
294
	// Generate the NT-HASH from the unicode string
295
	$user['nt-hash'] = bin2hex(mhash(MHASH_MD4, $ustr));
296
}
297

    
298
function local_user_get_groups($user, $all = false) {
299
	global $debug, $config;
300

    
301
	$groups = array();
302
	if (!is_array($config['system']['group']))
303
		return $groups;
304

    
305
	foreach ($config['system']['group'] as $group)
306
		if ( $all || ( !$all && ($group['name'] != "all")))
307
			if (is_array($group['member']))
308
				if (in_array($user['uid'], $group['member']))
309
					$groups[] = $group['name'];
310

    
311
	sort($groups);
312

    
313
	return $groups;
314
	
315
}
316

    
317
function local_user_set_groups($user, $new_groups = NULL ) {
318
	global $debug, $config, $groupindex;
319

    
320
	if (!is_array($config['system']['group']))
321
		return;
322

    
323
	$cur_groups = local_user_get_groups($user);
324
	$mod_groups = array();
325

    
326
	if (!is_array($new_groups))
327
		$new_groups = array();
328

    
329
	if (!is_array($cur_groups))
330
		$cur_groups = array();
331

    
332
	/* determine which memberships to add */
333
	foreach ($new_groups as $groupname) {
334
		if (in_array($groupname,$cur_groups))
335
			continue;
336
		$group = & $config['system']['group'][$groupindex[$groupname]];
337
		$group['member'][] = $user['uid'];
338
		$mod_groups[] = $group;
339
	}
340

    
341
	/* determine which memberships to remove */
342
	foreach ($cur_groups as $groupname) {
343
		if (in_array($groupname,$new_groups))
344
		continue;
345
		$group = & $config['system']['group'][$groupindex[$groupname]];
346
		$index = array_search($user['uid'], $group['member']);
347
		array_splice($group['member'], $index, 1);
348
		$mod_groups[] = $group;
349
	}
350

    
351
	/* sync all modified groups */
352
	foreach ($mod_groups as $group)
353
		local_group_set($group);
354
}
355

    
356
function local_group_set($group, $reset = false) {
357
	global $debug;
358

    
359
	$group_name = $group['name'];
360
	$group_gid = $group['gid'];
361
	$group_members = "''";
362
	if (!$reset && count($group['member']))
363
		$group_members = implode(",",$group['member']);
364

    
365
	/* read from group db */
366
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
367
	$pwread = fgets($fd);
368
	pclose($fd);
369

    
370
	/* determine add or mod */
371
	if (!strncmp($pwread, "pw:", 3))
372
		$group_op = "groupadd";
373
	else
374
		$group_op = "groupmod";
375

    
376
	/* add or mod group db */
377
	$cmd = "/usr/sbin/pw {$group_op} {$group_name} -g {$group_gid} -M {$group_members} 2>&1";
378

    
379
	if($debug)
380
		log_error("Running: {$cmd}");
381
	$fd = popen($cmd, "w");
382
	fwrite($fd, $user['password']);
383
	pclose($fd);
384

    
385
}
386

    
387
function local_group_del($group) {
388
	global $debug;
389

    
390
	/* delete from group db */
391
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
392

    
393
	if($debug)
394
		log_error("Running: {$cmd}");
395
	$fd = popen($cmd, "w");
396
	fwrite($fd, $user['password']);
397
	pclose($fd);
398

    
399
}
400

    
401
function ldap_test_connection() {
402
	global $debug, $config, $g;
403

    
404
	$ldapserver = $config['system']['webgui']['ldapserver'];
405
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
406
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
407

    
408
	if (!($ldap = ldap_connect($ldapserver)))
409
		return false;
410

    
411
	return true;
412
}
413

    
414
function ldap_test_bind() {
415
	global $debug, $config, $g;
416

    
417
	$ldapserver = $config['system']['webgui']['ldapserver'];
418
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
419
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
420
    
421
	if (!($ldap = ldap_connect($ldapserver)))
422
		return false;
423

    
424
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
425
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
426
    
427
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw)))
428
		return false;
429

    
430
	return true;
431
}
432

    
433
function ldap_get_user_ous($show_complete_ou=true) {
434
	global $debug, $config, $g;
435

    
436
	if(!function_exists("ldap_connect"))
437
		return;
438

    
439
	$ldapserver     = $config['system']['webgui']['ldapserver'];
440
	$ldapbindun     = $config['system']['webgui']['ldapbindun'];
441
	$ldapbindpw     = $config['system']['webgui']['ldapbindpw'];
442
	$ldapsearchbase = "{$config['system']['webgui']['ldapsearchbase']}";
443
	$ldaptype       = $config['system']['webgui']['backend'];
444

    
445
	$ldapfilter = "(ou=*)";
446
	putenv('LDAPTLS_REQCERT=never');
447
	if (!($ldap = ldap_connect($ldapserver))) {
448
		log_error("ERROR!  ldap_get_groups() could not connect to server {$ldapserver}.  Defaulting to built-in local_backed()");
449
		$status = local_backed($username, $passwd);
450
		return $status;
451
	}
452

    
453
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
454
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
455

    
456
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
457
		log_error("ERROR! ldap_get_groups() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
458
		$status = local_backed($username, $passwd);
459
		return $status;
460
	}
461

    
462
	$search = ldap_search($ldap, $ldapsearchbase, $ldapfilter);
463

    
464
	$info = ldap_get_entries($ldap, $search);
465

    
466
	$ous = array();
467

    
468
	if (is_array($info)) {
469
		foreach ($info as $inf) {
470
			if (!$show_complete_ou) {
471
				$inf_split = split(",", $inf['dn']);
472
				$ou = $inf_split[0];
473
				$ou = str_replace("OU=","", $ou);
474
			} else
475
				if($inf['dn'])
476
					$ou = $inf['dn'];
477
			if($ou)
478
				$ous[] = $ou;
479
		}
480
	}
481

    
482
	//Tack on the default Users container for AD since its non-standard
483
	if($ldaptype == 'ldap')
484
		$ous[] = "CN=Users,".$ldapsearchbase;
485

    
486
	return $ous;
487
}
488

    
489
function ldap_get_groups($username) {
490
	global $debug, $config;
491
	
492
	if(!function_exists("ldap_connect"))
493
		return;
494
	
495
	if(!$username) 
496
		return false;
497

    
498
	if(stristr($username, "@")) {
499
		$username_split=split("\@", $username);
500
		$username = $username_split[0];		
501
	}
502

    
503
	if(stristr($username, "\\")) {
504
		$username_split=split("\\", $username);
505
		$username = $username_split[0];        
506
	}    
507
	
508
	//log_error("Getting LDAP groups for {$username}.");
509
	
510
	$ldapserver         = $config['system']['webgui']['ldapserver'];
511
	$ldapbindun         = $config['system']['webgui']['ldapbindun'];
512
	$ldapbindpw         = $config['system']['webgui']['ldapbindpw'];
513
	$ldapfilter         = $config['system']['webgui']['ldapfilter'];
514
	$ldapfilter         = str_replace("\$username", $username, $ldapfilter);
515
	$ldapgroupattribute = $config['system']['webgui']['ldapgroupattribute'];
516
	$ldapdn             = $_SESSION['ldapdn'];
517
	 
518
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
519
	$ldapgroupattribute = strtolower($ldapgroupattribute);
520

    
521
	/* connect and see if server is up */
522
	putenv('LDAPTLS_REQCERT=never');
523
	if (!($ldap = ldap_connect($ldapserver))) {
524
		log_error("ERROR!  ldap_get_groups() could not connect to server {$ldapserver}.  Defaulting to built-in local_backed()");
525
		$status = local_backed($username, $passwd);
526
		return $status;	
527
	}
528
    
529
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
530
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
531

    
532
	/* bind as user that has rights to read group attributes */
533
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
534
		log_error("ERROR! ldap_get_groups() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
535
		$status = local_backed($username, $passwd);
536
		return $status;
537
	}
538

    
539
	/* get groups from DN found */
540
	/* use ldap_read instead of search so we don't have to do a bunch of extra work */
541
	/* since we know the DN is in $_SESSION['ldapdn'] */
542
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
543
	$search    = ldap_read($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
544
	$info      = ldap_get_entries($ldap, $search);
545

    
546
	$countem = $info["count"];	
547
	$memberof = array();
548
	
549
	if(is_array($info[0][$ldapgroupattribute])) {
550
		/* Iterate through the groups and throw them into an array */
551
		foreach ($info[0][$ldapgroupattribute] as $member) {
552
			if (stristr($member, "CN=") !== false) {
553
				$membersplit = split(",", $member);
554
				$memberof[] = preg_replace("/CN=/i", "", $membersplit[0]);
555
			}
556
		}
557
	}
558
	
559
	/* Time to close LDAP connection */
560
	ldap_close($ldap);
561
	
562
	$groups = print_r($memberof,true);
563
	
564
	//log_error("Returning groups ".$groups." for user $username");
565
	
566
	return $memberof;
567
}
568

    
569
function ldap_backed($username, $passwd) {
570
	global $debug, $config;
571
	
572
	if(!$username) 
573
		return;
574

    
575
	if(!function_exists("ldap_connect"))
576
		return;
577

    
578
	$adbindas = $username;
579
    
580
	if(stristr($username, "@")) {
581
		$username_split=split("\@", $username);
582
		$username = $username_split[0];        
583
	}
584
	if(stristr($username, "\\")) {
585
		$username_split=split("\\", $username);
586
		$username = $username_split[0];        
587
	}
588

    
589
	$ldapserver         = $config['system']['webgui']['ldapserver'];
590
	$ldapbindun         = $config['system']['webgui']['ldapbindun'];
591
	$ldapbindpw         = $config['system']['webgui']['ldapbindpw'];
592
	$ldapauthcont       = $config['system']['webgui']['ldapauthcontainers'];   
593
	$ldapnameattribute  = $config['system']['webgui']['ldapnameattribute'];  
594
	$ldapfilter         = $config['system']['webgui']['ldapfilter'];
595
	$ldaptype           = $config['system']['webgui']['backend'];
596
	$ldapfilter = str_replace("\$username", $username, $ldapfilter);
597

    
598
	/* first check if there is even an LDAP server populated */ 
599
	if(!$ldapserver) {
600
		log_error("ERROR!  ldap_backed() backed selected with no LDAP authentication server defined.  Defaulting to built-in local_backed().     Visit System -> User Manager -> Settings.");
601
		$status = local_backed($username, $passwd);
602
		return $status;
603
	}
604
	
605
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
606
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
607

    
608
	/* Make sure we can connect to LDAP */
609
	putenv('LDAPTLS_REQCERT=never');
610
	if (!($ldap = ldap_connect($ldapserver))) {
611
		log_error("ERROR!  ldap_backed() could not connect to server {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed().     Visit System -> User Manager -> Settings.");
612
		$status = local_backed($username, $passwd);		
613
		return $status;	
614
	}
615
	/* ok, its up.  now, lets bind as the bind user so we can search it */
616
	if (!($res = ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
617
		log_error("ERROR! ldap_backed() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
618
		ldap_close($ldap);
619
		$status = local_backed($username, $passwd);
620
		return $status;
621
	}
622
	
623
	/* Get LDAP Authcontainers and split em up. */
624
	$ldac_split = split(";", $ldapauthcont);
625
	
626
	/* now count how many there are */
627
	$containers = count($ldac_split);
628
	log_error("Number of Authentication Containers to search for $username is {$containers}");
629
	
630
	/* setup the usercount so we think we havn't found anyone yet */
631
	$usercount  = 0;
632

    
633
	/******************************/
634
	/* Currently LDAP Types are   */
635
	/* LDAP = Active Directory    */
636
	/* LDAPOTHER = eDir/Openldap  */
637
	/******************************/      
638
        
639
	/*****************************************************************/
640
	/* Now Active Directory We keep this seperate for future addons. */
641
	/*****************************************************************/
642
	/* Now LDAP other.  eDirectory or Netscape or Sunone or OpenLDAP */
643
	/*****************************************************************/
644
	/*  We First find the user based on username and filter          */
645
	/*  Then, once we find the first occurance of that person        */
646
	/*  We set seesion variables to ponit to the OU and DN of the    */
647
	/*  Person.  To later be used by ldap_get_groups.                */
648
	/*  that way we don't have to search twice.                      */
649
	/*****************************************************************/
650
	if ($ldaptype == 'ldap'){
651
		log_error("Now Searching for {$username} in Active directory.");
652
		/* Iterate through the user containers for search */
653
		for ($i=0;$i<$containers;$i++){
654
			/* Make sure we just use the first user we find */
655
			log_error("Now Searching in {$ldac_split[$i]} for {$ldapfilter}.");
656
			$search	 = ldap_search($ldap,$ldac_split[$i],$ldapfilter);
657
			$info	 = ldap_get_entries($ldap,$search);
658
			$matches = $info['count'];
659
			log_error("Matches Found = {$matches}");
660
			if ($matches == 1){
661
				$_SESSION['ldapdn'] = $info[0]['dn'];
662
				$_SESSION['ldapou'] = $ldac_split[$i];
663
				$_SESSION['ldapon'] = "true";
664
				$ldapdn = $_SESSION['ldapdn'];
665
				$userou = $_SESSION['ldapou'];
666
				break;
667
			}
668
		}
669

    
670
		if ($matches == 1){
671
			$binduser = $adbindas;
672
			log_error("Going to login as {$username} - DN = {$_SESSION['ldapdn']}");
673
		}
674
		if ($matches != 1){
675
			log_error("ERROR! Either LDAP search failed, or multiple users were found");
676
			$status = local_backed($username, $passwd);
677
			$_SESSION['ldapon'] = "false";
678
			ldap_close($ldap);
679
			return $status;                         
680
		}
681
	}
682

    
683
	/*****************************************************************/
684
	/* Now LDAP other.  eDirectory or Netscape or Sunone or OpenLDAP */
685
	/*****************************************************************/
686
	/*  We First find the user based on username and filter          */
687
	/*  Then, once we find the first occurance of that person        */
688
	/*  We set seesion variables to ponit to the OU and DN of the    */
689
	/*  Person.  To later be used by ldap_get_groups.                */
690
	/*  that way we don't have to search twice.                      */
691
	/*****************************************************************/
692
	if ($ldaptype == 'ldapother'){
693
		log_error("Now Searching for {$username} in LDAP.");
694
		/* Iterate through the user containers for search */
695
		for ($i=0;$i<$containers;$i++){
696
			/* Make sure we just use the first user we find */
697
			log_error("Now searching in {$ldac_split[$i]} for {$ldapfilter}.");
698
			$search  = ldap_search($ldap,$ldac_split[$i],$ldapfilter);
699
            $info    = ldap_get_entries($ldap,$search);
700
            $matches = $info['count'];
701
            log_error("Matches Found = {$matches}.");
702
                                      
703
			if ($matches == 1){
704
				$_SESSION['ldapdn'] = $info[0]['dn'];
705
				$_SESSION['ldapou'] = $ldac_split[$i];
706
				$_SESSION['ldapon'] = "true";
707
				$ldapdn = $_SESSION['ldapdn'];
708
				$userou = $_SESSION['ldapou'];
709
				break;
710
			}
711
		}
712
		if($matches == 1){
713
			$binduser = $ldapnameattribute."=".$username.",".$userou;
714
			log_error("Going to login as {$username} - DN = {$_SESSION['ldapdn']}");
715
		}
716
		if($matches != 1){
717
			log_error("ERROR! Either LDAP search failed, or multiple users were found");
718
			$status = local_backed($username, $passwd);
719
			ldap_close($ldap);
720
			$_SESSION['ldapon'] = "false";
721
			return $status;                         
722
		}
723
	}
724
	
725
	/* Now lets bind as the user we found */
726
	if (!($res = @ldap_bind($ldap, $binduser, $passwd))) {
727
		log_error("ERROR!  ldap_backed() could not bind to {$ldapserver} - {$username} - {$passwd}.  Defaulting to built-in local_backed().    Visit System -> User Manager -> Settings.");
728
		$status = local_backed($username, $passwd);
729
		return $status;
730
	}
731

    
732
	log_error("$binduser succesfully logged in via LDAP.");
733

    
734
	/* At this point we are bound to LDAP so the user was auth'd okay. */
735
	return true;
736
}
737

    
738
function radius_backed($username, $passwd){
739
	global $debug, $config, $debug;
740
	$ret = false;
741
	$radiusservers = $config['system']['radius']['servers'];
742

    
743
	$rauth = new Auth_RADIUS_PAP($username, $passwd);
744
	/* Add a new servers to our instance */
745
	foreach ($radiusservers as $radsrv)
746
		$rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
747

    
748
	if (!$rauth->start()) {
749
		$retvalue['auth_val'] = 1;
750
		$retvalue['error'] = $rauth->getError();
751
		if ($debug)
752
			printf("Radius start: %s<br>\n", $retvalue['error']);
753
	}
754

    
755
	// XXX - billm - somewhere in here we need to handle securid challenge/response
756

    
757
	/* Send request */
758
	$result = $rauth->send();
759
	if (PEAR::isError($result)) {
760
		$retvalue['auth_val'] = 1;
761
		$retvalue['error'] = $result->getMessage();
762
		if ($debug)
763
			printf("Radius send failed: %s<br>\n", $retvalue['error']);
764
	} else if ($result === true) {
765
		$retvalue['auth_val'] = 2;
766
		if ($debug)
767
			printf(gettext("Radius Auth succeeded")."<br>\n");
768
		$ret = true;
769
	} else {
770
		$retvalue['auth_val'] = 3;
771
		if ($debug)
772
			printf(gettext("Radius Auth rejected")."<br>\n");
773
	}
774

    
775
	// close OO RADIUS_AUTHENTICATION
776
	$rauth->close();
777

    
778
	return $ret;
779
}
780

    
781
function session_auth($backing) {
782
	global $g, $debug, $HTTP_SERVER_VARS, $userindex, $config;
783

    
784
	session_start();
785

    
786
	/* Validate incoming login request */
787
	if (isset($_POST['login'])) {
788
		if ($backing($_POST['usernamefld'], $_POST['passwordfld'])) {
789
			$_SESSION['Logged_In'] = "True";
790
			$_SESSION['Username'] = $_POST['usernamefld'];
791
			$_SESSION['last_access'] = time();
792
			log_error("Successful login for user '{$_POST['usernamefld']}' from: {$_SERVER['REMOTE_ADDR']}");
793
		} else {
794
			/* give the user a more detailed error message */
795
			if (isset($userindex[$_POST['usernamefld']])) {
796
				$_SESSION['Login_Error'] = "Username or Password incorrect";
797
				log_error("Wrong password entered for user '{$_POST['usernamefld']}' from: {$_SERVER['REMOTE_ADDR']}");
798
				if(isAjax()) {
799
					echo "showajaxmessage('{$_SESSION['Login_Error']}');";
800
					return;
801
				}
802
			} else {
803
				$_SESSION['Login_Error'] = "Username or Password incorrect";
804
				log_error("Attempted login for invalid user '{$_POST['usernamefld']}' from: {$_SERVER['REMOTE_ADDR']}");
805
				if(isAjax()) {
806
					echo "showajaxmessage('{$_SESSION['Login_Error']}');";
807
					return;
808
				}
809
			}
810
		}
811
	}
812

    
813
	/* Show login page if they aren't logged in */
814
	if (empty($_SESSION['Logged_In'])) {
815
		/* Don't display login forms to AJAX */
816
		if (isAjax())
817
			return false;
818
		require_once("authgui.inc");
819
		display_login_form();
820
		return false;
821
	}
822

    
823
	/* If session timeout isn't set, we don't mark sessions stale */
824
	if (!isset($config['system']['webgui']['session_timeout']) ||
825
		$config['system']['webgui']['session_timeout'] == 0 ||
826
		$config['system']['webgui']['session_timeout'] == "")
827
		$_SESSION['last_access'] = time();
828
	else {
829
		/* Check for stale session */
830
		if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
831
			$_GET['logout'] = true;
832
			$_SESSION['Logout'] = true;
833
		} else {
834
			/* only update if it wasn't ajax */
835
			if (!isAjax())
836
				$_SESSION['last_access'] = time();
837
		}
838
	}
839

    
840
	/* obtain user object */
841
	$user = getUserEntry($_SESSION['Username']);
842

    
843
	/* user hit the logout button */
844
	if (isset($_GET['logout'])) {
845

    
846
		if ($_SESSION['Logout'])
847
			log_error("Session timed out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
848
		else
849
			log_error("User logged out for user '{$_SESSION['Username']}' from: {$_SERVER['REMOTE_ADDR']}");
850

    
851
		/* wipe out $_SESSION */
852
		$_SESSION = array();
853

    
854
		if (isset($_COOKIE[session_name()]))
855
			setcookie(session_name(), '', time()-42000, '/');
856

    
857
		/* and destroy it */
858
		session_destroy();
859

    
860
		$scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
861
		$scriptElms = count($scriptName);
862
		$scriptName = $scriptName[$scriptElms-1];
863

    
864
		if (isAjax())
865
			return false;
866

    
867
		/* redirect to page the user is on, it'll prompt them to login again */
868
		pfSenseHeader($scriptName);
869

    
870
		return false;
871
	}
872

    
873
	/*
874
	 * this is for debugging purpose if you do not want to use Ajax
875
	 * to submit a HTML form. It basically diables the observation
876
	 * of the submit event and hence does not trigger Ajax.
877
	 */
878
	if ($_GET['disable_ajax']) {
879
		$_SESSION['NO_AJAX'] = "True";
880
		$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
881
		return true;
882
	}
883

    
884
	/*
885
	 * Same to re-enable Ajax.
886
	 */
887
	if ($_GET['enable_ajax']) {
888
		unset($_SESSION['NO_AJAX']);
889
		$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
890
		return true;
891
	}
892

    
893
	$HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
894
	return true;
895
}
896

    
897
?>
(4-4/40)