Project

General

Profile

Download (29.9 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
*/
37
38
require_once("functions.inc");
39
$groupindex = index_groups();
40
$userindex = index_users();
41
42
function logout_session() {
43
	global $_SESSION;
44
	
45
      if (hasLockAbility($_SESSION['Username'])) {
46
        unlink_if_exists("{$g['tmp_path']}/webconfigurator.lock");
47
      }
48
49
      /* wipe out $_SESSION */
50
      $_SESSION = array();
51
52
      /* and destroy it */
53
      session_destroy();
54
55
      $scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
56
      $scriptElms = count($scriptName);
57
      $scriptName = $scriptName[$scriptElms-1];
58
}
59
60
function getAllowedGroups($logged_in_user) {
61
	global $g, $config;
62
63
	if(!function_exists("ldap_connect"))
64
		return;
65
	
66
	$allowed = array();
67
	$allowed_groups = array();
68
	
69
	log_error("Getting groups for {$logged_in_user}.");
70
	
71
	$local_user = false;
72
	
73
	foreach($config['system']['user'] as $username) 
74
		if($username['name'] == $logged_in_user) 
75
			$local_user = true;
76
	
77
	/* return ldap groups if we are in ldap mode */
78
	if($config['system']['webgui']['backend'] == "ldap" && $local_user == false) {
79
		$allowed_groups = ldap_get_groups($logged_in_user);
80
		$fdny = fopen("/tmp/groups","w");
81
		fwrite($fdny, print_r($allowed, true));
82
		fclose($fdny);
83
		$allowed = array();
84
		if(is_array($config['system']['group']) && is_array($allowed_groups)) {
85
			foreach($config['system']['group'] as $group) {
86
				if(in_array($group['name'], $allowed_groups)) {
87
					foreach($group['pages'] as $page) {
88
						$allowed[] = $page;
89
					}				
90
				}
91
			}
92
		}
93
		return $allowed;
94
	}
95
	if($config['system']['webgui']['backend'] == "ldapother" && $local_user == false) {
96
		$allowed_groups = ldap_get_groups($logged_in_user);
97
		$fdny = fopen("/tmp/groups","w");
98
		fwrite($fdny, print_r($allowed, true));
99
		fclose($fdny);
100
		$allowed = array();
101
		if(is_array($config['system']['group']) && is_array($allowed_groups)) {
102
			foreach($config['system']['group'] as $group) {
103
				if(in_array($group['name'], $allowed_groups)) {
104
					foreach($group['pages'] as $page) {
105
						$allowed[] = $page;
106
					}				
107
				}
108
			}
109
		}
110
		return $allowed;
111
	}	
112
	
113
	$final_allowed = array();
114
115
	foreach($config['system']['user'] as $username) {
116
		if($username['name'] == $logged_in_user) 
117
			$allowed_groups  = explode(",", $username['groupname']);
118
	}
119
		
120
	foreach($config['system']['group'] as $group) {
121
		if(in_array($group['name'], $allowed_groups)) {
122
			foreach($group['pages'] as $page) {
123
				$allowed[] = $page;
124
			}
125
		}
126
	}
127
	
128
	return $allowed;
129
}
130
131
function &getSystemAdminNames() {
132
  global $config, $g, $userindex;
133
  $adminUsers = array();
134
135
  if (is_array($config['system']['user'])) {
136
    foreach($config['system']['user'] as $user){
137
      if (isSystemAdmin($user['name'])) {
138
        $adminUsers[] = $user['name'];
139
      }
140
    }
141
  }
142
143
  return $adminUsers;
144
}
145
146
function &getSystemPrivs() {
147
  global $g;
148
149
  $privs = array();
150
151
  $privs[] = array("id" => "lockwc",
152
                   "name" => "Lock webConfigurator",
153
                   "desc" => "Indicates whether this user will lock access to " .
154
                             "the webConfigurator for other users.");
155
  $privs[] = array("id" => "lock-ipages",
156
                   "name" => "Lock individual pages",
157
                   "desc" => "Indicates whether this user will lock individual " .
158
                              "HTML pages after having accessed a particular page" .
159
                              "(the lock will be freed if the user leaves or " .
160
                              "saves the page form).");
161
  $privs[] = array("id" => "hasshell",
162
                   "name" => "Has shell access",
163
                   "desc" => "Indicates whether this user is able to login for " .
164
                   "example via SSH.");
165
  $privs[] = array("id" => "copyfiles",
166
                   "name" => "Is allowed to copy files",
167
                   "desc" => "Indicates whether this user is allowed to copy files " .
168
                             "onto the {$g['product_name']} appliance via SCP/SFTP. " .
169
                             "If you are going to use this privilege, you must install " .
170
                             "scponly on the appliance (Hint: pkg_add -r scponly).");
171
  $privs[] = array("id" => "isroot",
172
                   "name" => "Is root user",
173
                   "desc" => "This user is associated with the UNIX root user " .
174
                             "(you should associate this privilege only with one " .
175
                             "single user).");
176
177
  return $privs;
178
}
179
180
function assignUID($username = "") {
181
  global $userindex, $config, $g;
182
183
  if ($username == "") { return; }
184
185
  $nextuid = $config['system']['nextuid'];
186
  $user =& $config['system']['user'][$userindex[$username]];
187
188
  if (empty($user['uid'])) {
189
    $user['uid'] = $nextuid;
190
    $nextuid++;
191
    $config['system']['nextuid'] = $nextuid;
192
193
    write_config();
194
195
    return $user;
196
  }
197
}
198
199
function assignGID($groupname = "") {
200
  global $groupindex, $config, $g;
201
202
  if ($groupname == "") { return; }
203
204
  $nextgid = $config['system']['nextgid'];
205
  $group =& $config['system']['group'][$groupindex[$groupname]];
206
207
  if (empty($group['gid'])) {
208
    $group['gid'] = $nextgid;
209
    $nextgid++;
210
    $config['system']['nextgid'] = $nextgid;
211
212
    write_config();
213
214
    return $group;
215
  }
216
}
217
218
function hasPrivilege($user, $privid = "") {
219
  global $userindex, $config, $g;
220
221
  if ($privid == "" || ! isset($userindex[$user])) { return 0; }
222
223
  $privs = &$config['system']['user'][$userindex[$user]]['priv'];
224
225
  if (is_array($privs)) {
226
    foreach($privs as $priv){
227
      if ($priv['id'] == $privid) {
228
        return 1;
229
      }
230
    }
231
  }
232
233
  return 0;
234
}
235
236
function isAllowedToCopyFiles($username) {
237
  global $userindex, $config, $g;
238
239
  if ($username == "") { return 0; }
240
241
  return hasPrivilege($username, "copyfiles");
242
}
243
244
function hasLockAbility($username) {
245
  global $userindex, $config, $g;
246
247
  if ($username == "") { return 0; }
248
249
  return hasPrivilege($username, "lockwc");
250
}
251
252
function hasPageLockAbility($username) {
253
  global $userindex, $config, $g;
254
255
  if ($username == "") { return 0; }
256
257
  return hasPrivilege($username, "lock-ipages");
258
}
259
260
function hasShellAccess($username) {
261
  global $userindex, $config, $g;
262
263
  if ($username == "") { return 0; }
264
265
  return hasPrivilege($username, "hasshell");
266
}
267
268
function isUNIXRoot($username = "") {
269
  global $userindex, $config;
270
271
  if ($username == "") { return 0; }
272
273
  if (isSystemAdmin($username)) {
274
    return hasPrivilege($username, "isroot");
275
  }
276
277
  return 0;
278
}
279
280
function setUserFullName($name = "", $new_name = "") {
281
  global $config, $g, $userindex;
282
283
  if ($name == "" || $new_name == "") { return; }
284
285
  $user = &$config['system']['user'][$userindex[$name]];
286
  $user['fullname'] = $new_name;
287
}
288
289
function setUserName($name = "", $new_name = "") {
290
  global $config, $g, $userindex;
291
292
  if ($name == "" || $new_name == "") { return; }
293
294
  $user = &$config['system']['user'][$userindex[$name]];
295
  $user['name'] = $new_name;
296
}
297
298
function setUserPWD($name = "", $password = "") {
299
  global $config, $g, $userindex;
300
301
  if ($name == "" || $password == "") { return; }
302
303
  $user = &$config['system']['user'][$userindex[$name]];
304
  $user['password'] = crypt($password);
305
}
306
307
function setUserGroupName($name = "", $new_name = "") {
308
  global $config, $g, $userindex;
309
310
  if ($name == "" || $new_name == "") { return; }
311
312
  $user = &$config['system']['user'][$userindex[$name]];
313
  $user['groupname'] = $new_name;
314
}
315
316
function setUserType($name = "", $new_type = "") {
317
  global $config, $g, $userindex;
318
319
  if ($name == "" || $new_type == "") { return; }
320
321
  $user = &$config['system']['user'][$userindex[$name]];
322
  $user['scope'] = $new_type;
323
}
324
325
function getUNIXRoot() {
326
  global $config, $g, $userindex;
327
328
  if (is_array($config['system']['user'])) {
329
    foreach($config['system']['user'] as $user){
330
      if (isUNIXRoot($user['name'])) {
331
        $root = &$config['system']['user'][$userindex[$user['name']]];
332
        return $root;
333
      }
334
    }
335
  }
336
337
  return NULL;
338
}
339
340
function getUNIXRootName() {
341
  global $config, $g, $userindex;
342
343
  if (is_array($config['system']['user'])) {
344
    foreach($config['system']['user'] as $user){
345
      if (isUNIXRoot($user['name'])) {
346
        return $user['name'];
347
      }
348
    }
349
  }
350
351
  return NULL;
352
}
353
354
function getGroupHomePage($group = "") {
355
  global $groupindex, $config, $g;
356
357
  if ($group == "") { return ""; }
358
359
  $page = $config['system']['group'][$groupindex[$group]]['home'];
360
  if(empty($page)) { $page = ""; }
361
  return $page;
362
}
363
364
function isSystemAdmin($username = "") {
365
  global $groupindex, $userindex, $config, $g, $_SESSION;
366
367
  if($_SESSION['isSystemAdmin']) 
368
	return $_SESSION['isSystemAdmin'];
369
370
  if(!function_exists("ldap_connect"))
371
	return;
372
373
  if($config['system']['webgui']['backend'] == "ldap") {
374
	$groups = ldap_get_groups($username);
375
	if(is_array($groups)){
376
		if(in_array("admins", $groups)) {
377
			$_SESSION['isSystemAdmin'] = true;
378
			return true;
379
		}
380
	}
381
  }
382
    if($config['system']['webgui']['backend'] == "ldapother") {
383
  	$groups = ldap_get_groups($username);
384
  	if(is_array($groups)){
385
  		if(in_array("admins", $groups)) {
386
  			$_SESSION['isSystemAdmin'] = true;
387
  			return true;
388
  		}
389
  	}
390
  }
391
392
  if ($username == "") { 
393
		$_SESSION['isSystemAdmin'] = false; 
394
		return 0; 
395
  }
396
397
  $gname = $config['system']['group'][$groupindex[$config['system']['user'][$userindex[$username]]['groupname']]]['name'];
398
399
  if (isset($gname)) {
400
	$_SESSION['isSystemAdmin'] = $gname === $g["admin_group"];
401
    return ($gname === $g["admin_group"]);
402
  }
403
404
  $_SESSION['isSystemAdmin'] = false; 
405
406
  return 0;
407
}
408
409
function getRealName($username = "") {
410
  global $userindex, $config;
411
412
  if ($username == "") { return ""; }
413
414
  return $config['system']['user'][$userindex[$username]]['fullname'];
415
416
}
417
418
function basic_auth($backing) {
419
  global $HTTP_SERVER_VARS;
420
421
  /* Check for AUTH_USER */
422
  if ($HTTP_SERVER_VARS['PHP_AUTH_USER'] <> "") {
423
    $HTTP_SERVER_VARS['AUTH_USER'] = $HTTP_SERVER_VARS['PHP_AUTH_USER'];
424
    $HTTP_SERVER_VARS['AUTH_PW'] = $HTTP_SERVER_VARS['PHP_AUTH_PW'];
425
  }
426
  if (!isset($HTTP_SERVER_VARS['AUTH_USER'])) {
427
    require_once("authgui.inc");
428
    header("WWW-Authenticate: Basic realm=\".\"");
429
    header("HTTP/1.0 401 Unauthorized");
430
    display_error_form("401", gettext("You must enter valid credentials to access this resource."));
431
    exit;
432
  } else {
433
    return $backing($HTTP_SERVER_VARS['AUTH_USER'],$HTTP_SERVER_VARS['AUTH_PW']);
434
  }
435
}
436
437
function session_auth($backing) {
438
  global $g, $HTTP_SERVER_VARS, $userindex, $config;
439
440
  session_start();
441
442
  /* Validate incoming login request */
443
  if (isset($_POST['login'])) {
444
    if ($backing($_POST['usernamefld'], $_POST['passwordfld'])) {
445
      $_SESSION['Logged_In'] = "True";
446
      $_SESSION['Username'] = $_POST['usernamefld'];
447
      $_SESSION['last_access'] = time();
448
    } else {
449
      /* give the user a more detailed error message */
450
      if (isset($userindex[$_POST['usernamefld']])) {
451
        $_SESSION['Login_Error'] = "Wrong password";
452
        if(isAjax()) {
453
        	echo "showajaxmessage('Wrong password');";
454
        	return;        	
455
        }
456
      } else {
457
        $_SESSION['Login_Error'] = "User does not exist";
458
        if(isAjax()) {
459
        	echo "showajaxmessage('User does not exist');";
460
        	return;
461
        }
462
      }
463
    }
464
  }
465
466
  /* Show login page if they aren't logged in */
467
  if (empty($_SESSION['Logged_In'])) {
468
    /* Don't display login forms to AJAX */
469
    if (isAjax())
470
      return false;
471
    require_once("authgui.inc");
472
    display_login_form();
473
    return false;
474
  } else {
475
    /* If session timeout isn't set, we don't mark sessions stale */
476
    if (!isset($config['system']['webgui']['session_timeout']) or
477
       $config['system']['webgui']['session_timeout'] == 0 or
478
       $config['system']['webgui']['session_timeout'] == "")
479
       $_SESSION['last_access'] = time();
480
     else
481
       /* Check for stale session */
482
       if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60)))
483
         $_GET['logout'] = true;
484
       else
485
         /* only update if it wasn't ajax */
486
         if (!isAjax())
487
           $_SESSION['last_access'] = time();
488
489
    /* user hit the logout button */
490
    if (isset($_GET['logout'])) {
491
      if (hasLockAbility($_SESSION['Username'])) {
492
        unlink_if_exists("{$g['tmp_path']}/webconfigurator.lock");
493
      }
494
495
      /* wipe out $_SESSION */
496
      $_SESSION = array();
497
498
      if (isset($_COOKIE[session_name()])) {
499
        setcookie(session_name(), '', time()-42000, '/');
500
      }
501
502
      /* and destroy it */
503
      session_destroy();
504
505
      $scriptName = split("/", $_SERVER["SCRIPT_FILENAME"]);
506
      $scriptElms = count($scriptName);
507
      $scriptName = $scriptName[$scriptElms-1];
508
509
      if (isAjax())
510
        return false;
511
512
      /* redirect to page the user is on, it'll prompt them to login again */
513
      pfSenseHeader($scriptName);
514
515
      return false;
516
517
    /* user wants to explicitely delete the log file.
518
     * Requires a particular privilege.
519
     */
520
    } else if ($_GET['deletelock'] && hasLockAbility($_SESSION['Username'])) {
521
      unlink_if_exists("{$g['tmp_path']}/webconfigurator.lock");
522
      $HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
523
      return true;
524
525
    /* this is for debugging purpose if you do not want to use Ajax
526
     * to submit a HTML form. It basically diables the observation
527
     * of the submit event and hence does not trigger Ajax.
528
     */
529
    } else if ($_GET['disable_ajax']) {
530
      $_SESSION['NO_AJAX'] = "True";
531
      $HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
532
      return true;
533
534
    /* Same to re-enable Ajax.
535
     */
536
    } else if ($_GET['enable_ajax']) {
537
      unset($_SESSION['NO_AJAX']);
538
      $HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
539
      return true;
540
541
    /* user wants to explicitely create a lock.
542
     * Requires a particular privilege.
543
     */
544
    } else if ($_GET['createlock'] && hasLockAbility($_SESSION['Username'])) {
545
      $fd = fopen("{$g['tmp_path']}/webconfigurator.lock", "w");
546
      fputs($fd, "{$_SERVER['REMOTE_ADDR']} (" .
547
                 getRealName($_SESSION['Username']) . ")");
548
      fclose($fd);
549
      /* if the user did delete the lock manually, do not
550
       * re-create it while the session is valide.
551
       */
552
      $_SESSION['Lock_Created'] = "True";
553
      $HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
554
      return true;
555
556
    /* proceed with the login process */
557
    } else {
558
      /* if the user is allowed to create a lock,
559
       * create it once per session.
560
       */
561
      if (hasLockAbility($_SESSION['Username']) &&
562
          ! isset($_SESSION['Lock_Created'])) {
563
564
        $fd = fopen("{$g['tmp_path']}/webconfigurator.lock", "w");
565
        fputs($fd, "{$_SERVER['REMOTE_ADDR']} (" .
566
                   getRealName($_SESSION['Username']) . ")");
567
        fclose($fd);
568
        /* if the user did delete the lock manually, do not
569
         * re-create it while the session is valide.
570
         */
571
        $_SESSION['Lock_Created'] = "True";
572
573
      /* give regular users a chance to automatically invalidate
574
       * a lock if its older than a particular time.
575
       */
576
      } else if (! hasLockAbility($_SESSION['Username']) &&
577
                 file_exists("{$g['tmp_path']}/webconfigurator.lock")) {
578
579
        $offset = 12; //hours
580
        $mtime = filemtime("{$g['tmp_path']}/webconfigurator.lock");
581
        $now_minus_offset = mktime(date("H") - $offset, 0, 0, date("m"), date("d"), date("Y"));
582
583
        if (($mtime - $now_minus_offset) < $mtime) {
584
          require_once("authgui.inc");
585
          display_login_form();
586
          return false;
587
        } else {
588
          /* file is older than mtime + offset which may
589
           * indicate a stale lockfile, hence we are going
590
           * to remove it.
591
           */
592
           unlink_if_exists("{$g['tmp_path']}/webconfigurator.lock");
593
        }
594
      }
595
596
      $HTTP_SERVER_VARS['AUTH_USER'] = $_SESSION['Username'];
597
      return true;
598
    }
599
  }
600
}
601
602
function pam_backed($username = "", $password = "") {
603
  /* do not allow blank passwords */
604
  if ($username == "" || password == "") { return false; }
605
606
  if(! extension_loaded( 'pam_auth' )) {
607
    if(! @dl( 'pam_auth.so' )) {
608
      return false;
609
    } else {
610
      /* no php file no auth, sorry */
611
      if (! file_exists("/etc/pam.d/php")) {
612
        if (! file_exists("/etc/pam.d")) { mkdir("/etc/pam.d"); }
613
614
        $pam_php = <<<EOD
615
# /etc/pam.d/php
616
#
617
# note: both an auth and account entry are required
618
619
# auth
620
auth            required        pam_nologin.so          no_warn
621
auth            sufficient      pam_opie.so             no_warn no_fake_prompts
622
auth            requisite       pam_opieaccess.so       no_warn allow_local
623
auth            required        pam_unix.so             no_warn try_first_pass
624
625
# account
626
account         required        pam_unix.so
627
628
# session
629
session         required        pam_permit.so
630
631
# password
632
password        required        pam_unix.so             no_warn try_first_pass
633
634
EOD;
635
636
        file_put_contents("/etc/pam.d/php", $pam_php);
637
      } // end if
638
639
      if (pam_auth($username, $password, &$error)) {
640
        return true;
641
      } else {
642
        return false;
643
      }
644
    }
645
  }
646
}
647
648
function passwd_backed($username, $passwd) {
649
  $authfile = file("/etc/master.passwd");
650
651
  $matches="";
652
653
  /* Check to see if user even exists */
654
  if(!($line = array_shift(preg_grep("/^$username:.*$/", $authfile))))
655
    return false;
656
657
  /* Get crypted password */
658
  preg_match("/^$username:((\\$1\\$[.\d\w_\/]{8}\\$)[.\d\w_\/]{22})$/", $line, $matches);
659
  $pass = $matches[1];
660
  $salt = $matches[2];
661
662
  /* Encrypt entered password with salt
663
   * And finally validate password
664
   */
665
  if ($pass == crypt($passwd, $salt))
666
    return true;
667
  else
668
    return false;
669
}
670
671
function ldap_test_connection() {
672
	global $config, $g;
673
674
	$ldapserver = $config['system']['webgui']['ldapserver'];
675
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
676
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
677
678
	if (!($ldap = ldap_connect($ldapserver))) {
679
		return false;
680
	}
681
682
	return true;
683
}
684
685
function ldap_test_bind() {
686
	global $config, $g;
687
688
    $ldapserver = $config['system']['webgui']['ldapserver'];
689
    $ldapbindun = $config['system']['webgui']['ldapbindun'];
690
    $ldapbindpw = $config['system']['webgui']['ldapbindpw'];
691
692
    if (!($ldap = ldap_connect($ldapserver))) {
693
		return false;
694
    }
695
696
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
697
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
698
699
    if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
700
		return false;
701
    }
702
703
	return true;
704
}
705
706
function ldap_get_user_ous($show_complete_ou=false) {
707
	global $config, $g;
708
709
	if(!function_exists("ldap_connect"))
710
		return;
711
712
    $ldapserver = $config['system']['webgui']['ldapserver'];
713
    $ldapbindun = $config['system']['webgui']['ldapbindun'];
714
    $ldapbindpw = $config['system']['webgui']['ldapbindpw'];
715
	$ldapsearchbase = "{$config['system']['webgui']['ldapsearchbase']}";
716
717
    $ldapfilter = "(ou=*)";
718
719
    if (!($ldap = ldap_connect($ldapserver))) {
720
        log_error("ERROR!  ldap_get_groups() could not connect to server {$ldapserver}.  Defaulting to built-in htpasswd_backed()");
721
            $status = htpasswd_backed($username, $passwd);
722
            return $status;
723
    }
724
725
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
726
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
727
728
    if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
729
        log_error("ERROR! ldap_get_groups() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in htpasswd_backed()");
730
            $status = htpasswd_backed($username, $passwd);
731
            return $status;
732
    }
733
734
    $search = ldap_search($ldap, $ldapsearchbase, $ldapfilter);
735
736
    $info = ldap_get_entries($ldap, $search);
737
738
	$ous = array();
739
740
	if(is_array($info)) {
741
	    foreach($info as $inf) {
742
			if(!$show_complete_ou) {
743
	            $inf_split = split(",", $inf['dn']);
744
	            $ou = $inf_split[0];
745
	            $ou = str_replace("OU=","", $ou);
746
			} else {
747
				if($inf['dn'])
748
					$ou = $inf['dn'];
749
			}
750
			if($ou)
751
				$ous[] = $ou;
752
	    }
753
	}
754
	
755
	$ous[] = "OU=Users," . $ldapsearchbase;
756
	
757
	return $ous;
758
	
759
}
760
761
function ldap_get_groups($username) {
762
	global $config;
763
	
764
	if(!function_exists("ldap_connect"))
765
		return;
766
	
767
	if(!$username) 
768
		return false;
769
770
	if(stristr($username, "@")) {
771
		$username_split=split("\@", $username);
772
		$username = $username_split[0];		
773
	}
774
	
775
	log_error("Getting LDAP groups for {$username}.");
776
	
777
	$ldapserver = $config['system']['webgui']['ldapserver'];
778
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
779
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
780
	$ldapfilter = $config['system']['webgui']['ldapfilter'];
781
	$ldapsearchbase = "{$config['system']['webgui']['ldapsearchbase']}";
782
	$ldapfilter = str_replace("\$username", $username, $ldapfilter);
783
	$ldapauthcontainers = $config['system']['webgui']['ldapauthcontainers'];
784
	$ldapgroupattribute = $config['system']['webgui']['ldapgroupattribute'];
785
 
786
        /*Convert attribute to lowercase.  php ldap arrays put everything in lowercase */
787
        $ldapgroupattribute = strtolower($ldapgroupattribute);
788
789
	if (!($ldap = ldap_connect($ldapserver))) {
790
	    log_error("ERROR!  ldap_get_groups() could not connect to server {$ldapserver}.  Defaulting to built-in htpasswd_backed()");
791
		$status = htpasswd_backed($username, $passwd);
792
		return $status;	
793
	}
794
	
795
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
796
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
797
798
	if (!($res = @ldap_bind($ldap, $ldapbindun, $ldapbindpw))) {
799
	    log_error("ERROR! ldap_get_groups() could not bind to {$ldapserver} - {$ldapfilter}.  Defaulting to built-in htpasswd_backed()");
800
		$status = htpasswd_backed($username, $passwd);
801
		return $status;
802
	}
803
804
	/* user specified login containers */
805
	$ldac_split = split(";", $ldapauthcontainers);
806
	$search = ldap_search($ldap, $ldapsearchbase, $ldapfilter);
807
	
808
	if(!$search) {
809
		log_error("ERROR!  Could not locate User group container for username {$username}.");
810
		log_error("        Please ensure that the needed container is defined in the ldap auth containers setting feature.");
811
		$status = htpasswd_backed($username, $passwd);
812
		return $status;	
813
	}
814
	
815
	$info = ldap_get_entries($ldap, $search);
816
817
	/* find home container */
818
    foreach($info as $inf) {
819
            $inf_split = split(",", $inf['dn']);
820
            $ou = $inf_split[1];
821
    }
822
823
	if(!$ou) {
824
		log_error("Could not resolve users home container for {$username}");
825
		$status = htpasswd_backed($username, $passwd);
826
		return $status;	
827
	}
828
829 43829638 Scott Ullrich
    log_error("LDAPGroupAttribute ===== {$ldapgroupattribute}");
830 b0ed07d1 Scott Ullrich
	$search = ldap_search($ldap, $ldapauthcontainers, $ldapfilter, array($ldapgroupattribute));
831
832 43829638 Scott Ullrich
	if($search) {
833
		$info = ldap_get_entries($ldap, $search);
834
    	$countem = $info["count"];	
835
	}
836 b0ed07d1 Scott Ullrich
	$memberof = array();
837
	
838 43829638 Scott Ullrich
	log_error("USER HAS {$countem} LDAP Groups it is {$info[0][$ldapgroupattribute][0]}");
839 b0ed07d1 Scott Ullrich
840
	if(is_array($info[0][$ldapgroupattribute])) {
841
    	foreach($info[0][$ldapgroupattribute] as $member) {
842
    	   //$member = strtoupper($member);
843
    	   log_error("MEMBER===={$member}");
844
            	if(stristr($member, "CN=") !== false) {
845
                    	$membersplit = split(",", $member);
846
                    	$memberof[] = preg_replace("/CN=/i", "", $membersplit[0]);
847
            	}
848
    	}
849
	}
850
	
851
	/* Time to close LDAP connection */
852
	ldap_close($ldap);
853
	
854
	$groups = print_r($memberof,true);
855
	
856
	log_error("Returning groups " . $groups  . " for user $username");
857
	
858
	return $memberof;
859
}
860
861
function ldap_backed($username, $passwd) {
862
	global $config;
863
	
864
	if(!$username) 
865
		return;
866
867
	if(!function_exists("ldap_connect"))
868
		return;
869
870
	$ldapserver = $config['system']['webgui']['ldapserver'];
871
	$ldapbindun = $config['system']['webgui']['ldapbindun'];
872
	$ldapbindpw = $config['system']['webgui']['ldapbindpw'];
873
        $ldapauthcont = $config['system']['webgui']['ldapauthcontainers'];   
874
        $ldapnameattribute = $config['system']['webgui']['ldapnameattribute'];     
875
    /* NEED TO FIGURE OUT LDAP TYPE */
876
    $ldaptype = $config['system']['webgui']['backend'];
877
    /********************************/
878
879
	if(!$ldapserver) {
880
		log_error("ERROR!  ldap_backed() backed selected with no LDAP authentication server defined.  Defaulting to built-in htpasswd_backed().     Visit System -> User Manager -> Settings.");
881
		$status = htpasswd_backed($username, $passwd);
882
		return $status;
883
	}
884
	
885
	if (!($ldap = ldap_connect($ldapserver))) {
886
	    log_error("ERROR!  ldap_backed() could not connect to server {$ldapserver} - {$ldapfilter}.  Defaulting to built-in htpasswd_backed().     Visit System -> User Manager -> Settings.");
887
		$status = htpasswd_backed($username, $passwd);
888
		return $status;	
889
	}
890
        /* TAKE AD INTO ACCOUNT */
891
	if ($ldaptype == 'ldap'){
892
	   $binduser = $username;
893
	}
894
	if ($ldaptype == 'ldapother'){
895
	   $binduser = $ldapnameattribute.'='.$username.','.$ldapauthcont;
896
	}
897
	log_error("BINDUSER ==== {$binduser}");
898
    	/************************/
899
	
900
	if (!($res = @ldap_bind($ldap, $binduser, $passwd))) {
901
	    log_error("ERROR!  ldap_backed() could not bind to {$ldapserver} - {$username} - {$passwd}.  Defaulting to built-in htpasswd_backed().    Visit System -> User Manager -> Settings.");
902
		$status = htpasswd_backed($username, $passwd);
903
		return $status;
904
	}
905
	
906
	log_error("$username logged in via LDAP.");
907
	log_error("$binduser ldap name logged in via LDAP.");
908
	/* At this point we are binded to LDAP so the user was auth'd okay. */
909
	return true;
910
}
911
912
function htpasswd_backed($username, $passwd) {
913
  $authfile = file("/var/run/htpasswd");
914
915
  /* sanity check to ensure that /usr/local/www/.htpasswd doesn't exist */
916
  unlink_if_exists("/usr/local/www/.htpasswd");
917
918
  $matches="";
919
  if(!($line = array_shift(preg_grep("/^$username:.*$/", $authfile))))
920
          return false;
921
922
  /* Get crypted password */
923
  preg_match("/^$username:((\\$1\\$[.\d\w_\/]{8}\\$)[.\d\w_\/]{22})$/", $line, $matches);
924
  $pass = $matches[1];
925
  $salt = $matches[2];
926
927
  /* Encrypt entered password with salt
928
   * And finally validate password
929
   */
930
  if ($pass == crypt($passwd, $salt))
931
    return true;
932
  else
933
    return false;
934
}
935
936
function radius_backed($username, $passwd){
937
  global $config, $debug;
938
  $ret = false;
939
  $radiusservers = $config['system']['radius']['servers'];
940
941
  $rauth = new Auth_RADIUS_PAP($username, $passwd);
942
  foreach ($radiusservers as $radsrv) {
943
    // Add a new server to our instance
944
    $rauth->addServer($radsrv['ipaddr'], $radsrv['port'], $radsrv['sharedsecret']);
945
  }
946
947
  if (!$rauth->start()) {
948
    $retvalue['auth_val'] = 1;
949
    $retvalue['error'] = $rauth->getError();
950
    if ($debug)
951
      printf("Radius start: %s<br>\n", $retvalue['error']);
952
  }
953
954
  // XXX - billm - somewhere in here we need to handle securid challenge/response
955
956
  // Send request
957
  $result = $rauth->send();
958
  if (PEAR::isError($result)) {
959
    $retvalue['auth_val'] = 1;
960
    $retvalue['error'] = $result->getMessage();
961
    if ($debug)
962
      printf("Radius send failed: %s<br>\n", $retvalue['error']);
963
  } else if ($result === true) {
964
    $retvalue['auth_val'] = 2;
965
    if ($debug)
966
      printf (gettext("Radius Auth succeeded") . "<br>\n");
967
    $ret = true;
968
  } else {
969
      $retvalue['auth_val'] = 3;
970
      if ($debug)
971
        printf (gettext("Radius Auth rejected") . "<br>\n");
972
  }
973
  // close OO RADIUS_AUTHENTICATION
974
  $rauth->close();
975
976
  return $ret;
977
}
978
979
980
function index_groups() {
981
  global $g, $config, $groupindex;
982
983
  $groupindex = array();
984
985
  if (isset($config['system']['group'])) {
986
    $i = 0;
987
    foreach($config['system']['group'] as $groupent) {
988
      $groupindex[$groupent['name']] = $i;
989
      $i++;
990
    }
991
  }
992
  return ($groupindex);
993
}
994
995
function index_users() {
996
  global $g, $config;
997
998
  if (isset($config['system']['user'])) {
999
    $i = 0;
1000
    foreach($config['system']['user'] as $userent) {
1001
      $userindex[$userent['name']] = $i;
1002
      $i++;
1003
    }
1004
  }
1005
  return ($userindex);
1006
}
1007
1008
?>