Project

General

Profile

Download (26.6 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
	$passwd = crypt($passwd, $user['password']);
117

    
118
	return ($passwd == $user['password']);
119
}
120

    
121
function local_sync_accounts() {
122
	global $debug, $config;
123
	conf_mount_rw();
124

    
125
	/* remove local users to avoid uid conflicts */
126
	$fd = popen("/usr/sbin/pw usershow -a", "r");
127
	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
			$cmd = "/usr/sbin/pw userdel {$line[2]}";
137
			if($debug)
138
				log_error("Running: {$cmd}");
139
			mwexec($cmd);
140
		}
141
		pclose($fd);
142
	}
143

    
144
	/* remove local groups to avoid gid conflicts */
145
	$gids = array();
146
	$fd = popen("/usr/sbin/pw groupshow -a", "r");
147
	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
			$cmd = "/usr/sbin/pw groupdel {$line[2]}";
157
			if($debug)
158
				log_error("Running: {$cmd}");
159
			mwexec($cmd);
160
		}
161
		pclose($fd);
162
	}
163

    
164
	/* make sure the all group exists */
165
	$allgrp = getGroupEntryByGID(1998);
166
	local_group_set($allgrp, true);
167

    
168
	/* sync all local users */
169
	if (is_array($config['system']['user']))
170
		foreach ($config['system']['user'] as $user)
171
			local_user_set($user);
172

    
173
	/* sync all local groups */
174
	if (is_array($config['system']['group']))
175
		foreach ($config['system']['group'] as $group)
176
			local_group_set($group);
177

    
178
	conf_mount_ro();
179

    
180
}
181

    
182
function local_user_set(& $user) {
183
	global $g, $debug;
184

    
185
	$home_base = "/home/";
186
	
187
	if (!is_dir($home_base)) 
188
		mkdir($home_base, 0755);
189
	
190
	$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

    
196
	/* configure shell type */
197
	if (!userHasPrivilege($user, "user-shell-access")) {
198
		if (!userHasPrivilege($user, "user-copy-files"))
199
			$user_shell = "/sbin/nologin";
200
		else
201
			$user_shell = "/usr/local/bin/scponly";
202
	}
203

    
204
	/* root user special handling */
205
	if ($user_uid == 0) {
206
		$cmd = "/usr/sbin/pw usermod -n root -s /bin/sh -H 0";
207
		if($debug)
208
			log_error("Running: {$cmd}");
209
		$fd = popen($cmd, "w");
210
		fwrite($fd, $user['password']);
211
		pclose($fd);
212
		$user_group = "wheel";
213
	}
214

    
215
	/* 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
			" -c ".escapeshellarg($user['fullname'])." -H 0 2>&1";
230

    
231
	if($debug)
232
		log_error("Running: {$cmd}");
233
	$fd = popen($cmd, "r+");
234
	fwrite($fd, $user['password']);
235
	pclose($fd);
236

    
237
	/* create user directory if required */
238
	if (!is_dir($user_home)) {
239
		mkdir($user_home, 0700);
240
		exec("cp /root/.* {$home_base}/");
241
	}
242
	chown($user_home, $user_name);
243
	chgrp($user_home, $user_group);
244

    
245
	/* 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
}
253

    
254
function local_user_del($user) {
255
	global $debug;
256
	/* remove all memberships */
257
	local_user_get_groups($user);
258

    
259
	/* delete from pw db */
260
	$cmd = "/usr/sbin/pw userdel {$user['name']}";
261

    
262
	if($debug)
263
		log_error("Running: {$cmd}");
264
	$fd = popen($cmd, "w");
265
	fwrite($fd, $user['password']);
266
	pclose($fd);
267
}
268

    
269
function local_user_set_password(& $user, $password) {
270

    
271
	$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
	global $debug, $config;
288

    
289
	$groups = array();
290
	if (!is_array($config['system']['group']))
291
		return $groups;
292

    
293
	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

    
299
	sort($groups);
300

    
301
	return $groups;
302
	
303
}
304

    
305
function local_user_set_groups($user, $new_groups = NULL ) {
306
	global $debug, $config, $groupindex;
307

    
308
	if (!is_array($config['system']['group']))
309
		return;
310

    
311
	$cur_groups = local_user_get_groups($user);
312
	$mod_groups = array();
313

    
314
	if (!is_array($new_groups))
315
		$new_groups = array();
316

    
317
	if (!is_array($cur_groups))
318
		$cur_groups = array();
319

    
320
	/* 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

    
329
	/* 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

    
339
	/* sync all modified groups */
340
	foreach ($mod_groups as $group)
341
		local_group_set($group);
342
}
343

    
344
function local_group_set($group, $reset = false) {
345
	global $debug;
346

    
347
	$group_name = $group['name'];
348
	$group_gid = $group['gid'];
349
	$group_members = "''";
350
	if (!$reset && count($group['member']))
351
		$group_members = implode(",",$group['member']);
352

    
353
	/* read from group db */
354
	$fd = popen("/usr/sbin/pw groupshow {$group_name} 2>&1", "r");
355
	$pwread = fgets($fd);
356
	pclose($fd);
357

    
358
	/* determine add or mod */
359
	if (!strncmp($pwread, "pw:", 3))
360
		$group_op = "groupadd";
361
	else
362
		$group_op = "groupmod";
363

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

    
367
	if($debug)
368
		log_error("Running: {$cmd}");
369
	$fd = popen($cmd, "r+");
370
	fwrite($fd, $user['password']);
371
	pclose($fd);
372

    
373
}
374

    
375
function local_group_del($group) {
376
	global $debug;
377

    
378
	/* delete from group db */
379
	$cmd = "/usr/sbin/pw groupdel {$group['name']}";
380

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

    
387
}
388

    
389
function ldap_test_connection() {
390
	global $debug, $config, $g;
391

    
392
	$ldapserver = $config['system']['webgui']['ldapserver'];
393
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
394
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
395

    
396
	if (!($ldap = ldap_connect($ldapserver)))
397
		return false;
398

    
399
	return true;
400
}
401

    
402
function ldap_test_bind() {
403
	global $debug, $config, $g;
404

    
405
	$ldapserver = $config['system']['webgui']['ldapserver'];
406
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
407
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
408
    
409
	if (!($ldap = ldap_connect($ldapserver)))
410
		return false;
411

    
412
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
413
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
414
    
415
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw)))
416
		return false;
417

    
418
	return true;
419
}
420

    
421
function ldap_get_user_ous($show_complete_ou=true) {
422
	global $debug, $config, $g;
423

    
424
	if(!function_exists("ldap_connect"))
425
		return;
426

    
427
	$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

    
433
	$ldapfilter = "(ou=*)";
434
	putenv('LDAPTLS_REQCERT=never');
435
	if (!($ldap = ldap_connect($ldapserver))) {
436
		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
		return $status;
439
	}
440

    
441
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
442
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
443

    
444
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
445
		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
		return $status;
448
	}
449

    
450
	$search = ldap_search($ldap, $ldapsearchbase, $ldapfilter);
451

    
452
	$info = ldap_get_entries($ldap, $search);
453

    
454
	$ous = array();
455

    
456
	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
				if($inf['dn'])
464
					$ou = $inf['dn'];
465
			if($ou)
466
				$ous[] = $ou;
467
		}
468
	}
469

    
470
	//Tack on the default Users container for AD since its non-standard
471
	if($ldaptype == 'ldap')
472
		$ous[] = "CN=Users,".$ldapsearchbase;
473

    
474
	return $ous;
475
}
476

    
477
function ldap_get_groups($username) {
478
	global $debug, $config;
479
	
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

    
491
	if(stristr($username, "\\")) {
492
		$username_split=split("\\", $username);
493
		$username = $username_split[0];        
494
	}    
495
	
496
	//log_error("Getting LDAP groups for {$username}.");
497
	
498
	$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
	$ldapgroupattribute = $config['system']['webgui']['ldapgroupattribute'];
504
	$ldapdn             = $_SESSION['ldapdn'];
505
	 
506
	/*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
507
	$ldapgroupattribute = strtolower($ldapgroupattribute);
508

    
509
	/* connect and see if server is up */
510
	putenv('LDAPTLS_REQCERT=never');
511
	if (!($ldap = ldap_connect($ldapserver))) {
512
		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
		return $status;	
515
	}
516
    
517
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
518
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
519

    
520
	/* bind as user that has rights to read group attributes */
521
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
522
		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
		return $status;
525
	}
526

    
527
	/* 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
	//$search    = ldap_read($ldap, $ldapdn, "(objectclass=*)", array($ldapgroupattribute));
531
	$search    = ldap_read($ldap, $ldapdn, $ldapfilter, array($ldapgroupattribute));
532
	$info      = ldap_get_entries($ldap, $search);
533

    
534
	$countem = $info["count"];	
535
	$memberof = array();
536
	
537
	if(is_array($info[0][$ldapgroupattribute])) {
538
		/* 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
	}
546
	
547
	/* Time to close LDAP connection */
548
	ldap_close($ldap);
549
	
550
	$groups = print_r($memberof,true);
551
	
552
	//log_error("Returning groups ".$groups." for user $username");
553
	
554
	return $memberof;
555
}
556

    
557
function ldap_backed($username, $passwd) {
558
	global $debug, $config;
559
	
560
	if(!$username) 
561
		return;
562

    
563
	if(!function_exists("ldap_connect"))
564
		return;
565

    
566
	$adbindas = $username;
567
    
568
	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
	$ldapserver         = $config['system']['webgui']['ldapserver'];
578
	$ldapbindun         = $config['system']['webgui']['ldapbindun'];
579
	$ldapbindpw         = $config['system']['webgui']['ldapbindpw'];
580
	$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
		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
		return $status;
591
	}
592
	
593
	ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
594
	ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
595

    
596
	/* Make sure we can connect to LDAP */
597
	putenv('LDAPTLS_REQCERT=never');
598
	if (!($ldap = ldap_connect($ldapserver))) {
599
		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
		return $status;	
602
	}
603
	/* ok, its up.  now, lets bind as the bind user so we can search it */
604
	if (!($res = ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
605
		log_error("ERROR! ldap_backed() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in local_backed()");
606
		ldap_close($ldap);
607
		$status = local_backed($username, $passwd);
608
		return $status;
609
	}
610
	
611
	/* Get LDAP Authcontainers and split em up. */
612
	$ldac_split = split(";", $ldapauthcont);
613
	
614
	/* now count how many there are */
615
	$containers = count($ldac_split);
616
	log_error("Number of Authentication Containers to search for $username is {$containers}");
617
	
618
	/* setup the usercount so we think we havn't found anyone yet */
619
	$usercount  = 0;
620

    
621
	/******************************/
622
	/* Currently LDAP Types are   */
623
	/* LDAP = Active Directory    */
624
	/* LDAPOTHER = eDir/Openldap  */
625
	/******************************/      
626
        
627
	/*****************************************************************/
628
	/* Now Active Directory We keep this seperate for future addons. */
629
	/*****************************************************************/
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
	if ($ldaptype == 'ldap'){
639
		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

    
658
		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
			$status = local_backed($username, $passwd);
665
			$_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
	if ($ldaptype == 'ldapother'){
681
		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
                                      
691
			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
			$status = local_backed($username, $passwd);
707
			ldap_close($ldap);
708
			$_SESSION['ldapon'] = "false";
709
			return $status;                         
710
		}
711
	}
712
	
713
	/* Now lets bind as the user we found */
714
	if (!($res = @ldap_bind($ldap, $binduser, $passwd))) {
715
		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
		return $status;
718
	}
719

    
720
	log_error("$binduser succesfully logged in via LDAP.");
721

    
722
	/* At this point we are bound to LDAP so the user was auth'd okay. */
723
	return true;
724
}
725

    
726
function radius_backed($username, $passwd){
727
	global $debug, $config, $debug;
728
	$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

    
743
	// 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

    
769
function session_auth($backing) {
770
	global $g, $debug, $HTTP_SERVER_VARS, $userindex, $config;
771

    
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
?>
(3-3/37)