1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
|
<?php
/*
LWAT, LDAP Webbased Administration Tool
Copyright (C) 2007 Finn-Arne Johansen <faj@bzz.no> BzzWare AS, Norway
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/***************************************************************************
* lwat_login - tries to log in user either given or stored admindn/adminpw
* lwat_key - Reads session key, or create a new one
* lwat_ldap - connects to the ldap-server, with proper options set
* reportLdapError - Reports error number and textual message of
* ldap error occured
* loadConfig - Loads configuration, either from config.php, or use
* predefined values
* loadLocale - Checks for browser language and tries to load locale
* xorstring - xors a string, to either crypt or decrypt data
* readKey - Decodes data posted through the web-browser
* debug - Displays data top debug through development
* pwgen - generates a random password
* cryptgen - generates a crypted password from a given password
* getnextid - fetch (and update) the next id to be used. This is
* stored in ldap under ou=variables
* get_sn - parses a full name, and fetches the surname
* chk_username - Checks if a given username is already taken
* get_username - generates a username from a fullname
* get_givenName - parses a fullname, and extract a givenName
* get_sambasid - looks up the sambasid to be used.
* ldapAddUser - Adds a user into ldap
* sambaAddInfo - Adds samba information for a user
* userAddGroup - Add a user into a group
***************************************************************************/
require_once ("createlm.php");
/**********************************************************************
* lwat_login - tries to log in user either given or stored
* admindn/adminpw
*****************
* Arguments
* ldap - ldap connection
* adminUser - the username to log in as
* admindn - password ?
* key - key used to xor the stored password
* Returns
* authenticated - True if logged in succesfully
*****************
* if AdminUser is given
* Loop while possible to look closer to base
* Try to look up the full dn of the admin user
* if found
* try to connect as the admin user
* if succesfull
* store admindn and admin pw
* return true
* look closer to the ldap base for a user
* return false
* if no stored admin dn
* return failure
* fetch stored password
* if able to bind using stored dn/pw
* update cookie
* return success
* return failure
**********************************************************************/
function lwat_login ($ldap, $adminUser, $adminpw, $key) {
global $base ;
if (!empty ($adminUser)) {
$loginbase = $base ;
$filter = '(|(&(objectClass=posixAccount)(uid=' . $adminUser . '))(&(objectClass=simpleSecurityObject)(cn=' . $adminUser . ')))' ;
$want = array ("dn") ;
while (!empty ($loginbase)) {
$result = @ldap_search($ldap, $loginbase, $filter, $want);
$entries = @ldap_get_entries ($ldap, $result);
$admindn = htmlspecialchars($entries[0]['dn']) ;
$bind = @ldap_bind ($ldap, $admindn, $adminpw);
if ($bind) {
$xorstring = xorstring ($key, $adminpw);
$packstring = unpack ("H*", $xorstring) ;
setcookie ('admindn', $admindn, time () + 1800) ;
setcookie ('xorstring', $packstring[1], time () + 1800) ;
return true ;
} else {
$loginbase = ldap_explode_dn ($loginbase,0) ;
array_splice ($loginbase, 0,2) ;
$loginbase = implode (",", $loginbase) ;
}
}
return false ;
}
$admindn = $_COOKIE['admindn'] ;
if (empty ($admindn))
return false ;
$packstring = $_COOKIE['xorstring'] ;
$xorstring = pack ("H*", $packstring);
$adminpw = xorstring ($key, $xorstring) ;
$bind = @ldap_bind ($ldap, $admindn, $adminpw);
if ($bind) {
setcookie ("admindn", $admindn, time () + 1800) ;
setcookie ("xorstring", $packstring, time () + 1800) ;
return true ;
}
return false ;
}
/**********************************************************************
* lwat_key - Reads session key, or create a new one
*****************
* Returns
* key - either read from session, or newlyt created
*****************
* Read key from session
* if no key found
* create new key
* store key in session
* return key value
**********************************************************************/
function lwat_key () {
if (isset($_SESSION['key']))
$key = $_SESSION['key'] ;
else {
$key = substr (crypt(sprintf (gettimeofday (true))),4) ;
$_SESSION['key'] = $key ;
}
return $key ;
}
/**********************************************************************
* lwat_ldap - connects to the ldap-server, with proper options set
*****************
* Returns
* ldap - ldap connection
*****************
* connect to ldap host
* set ldap options
* if not tls is available
* check error
* error 2: tls not available, ignore ?
* error 81: unable to contact ldap server
* other error:
* report ldaperror
*
* if error
* close conection
* return 0
* return ldap connection
**********************************************************************/
function lwat_ldap () {
global $ldaphost, $tlsRequire ;
$ldaperr = 0 ;
$ldap=ldap_connect ($ldaphost);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
if ($tlsRequire) {
if (!@ldap_start_tls($ldap)) {
$ldaperr = ldap_errno ($ldap) ;
switch ($ldaperr) {
case 2:
printf (_("Unable to start encrypted connection with the ldapserver"), $ldaphost) ;
break ;
case 81:
printf (_("Sorry, but we are not able to contact your ldapserver running on the host <B>%s</B>"), $ldaphost) ;
break ;
default:
reportLdapError (ldap_errno ($ldap), "Tried to connect") ;
break ;
}
}
}
if ($ldaperr) {
ldap_close ($ldap) ;
die ("<BR />" . _("Please check your configuration")) ;
}
return $ldap ;
}
/**********************************************************************
* reportLdapError - Reports error number and textual message of
* ldap error occured
*****************
* Arguments:
* ldaperr - Error code from ldap
* myAction - Description of what lead to the error from lwat
*****************
* Display an error message to the user
* Also display links to
* search lwat tickets for previously reported errors
* create a new ticket with some debug information
**********************************************************************/
function reportLdapError ($ldaperr, $myAction) {
printf (_("An Unknown error occured.") . "<BR />") ;
printf (_("The error code from ldap was: %d") . "<BR />", $ldaperr) ;
printf (_("The error string from ldap was: %s") ."<BR>", ldap_err2str ($ldaperr));
printf (_("You may <A href='%s' target=_blank>search</A> for the error among the lwat tickets, or if not found, consider <A href='%s'>reporting</A> it"),
sprintf ("http://lwat.org/cgi-bin/trac.cgi/search?ticket=on&q=%%22Error %d when %s%%22", $ldaperr, $myAction),
sprintf ("mailto:trac@lwat.org?subject=Error %d when %s&Body=The error message was:%%0A%s", $ldaperr, $myAction, ldap_err2str($ldaperr))) ;
}
/***************************************************************************
* loadConfig - Loads configuration, either from config.php, or use
* predefined values
***********************
* Load predefined values
* if config.php exists load settings
**************************************************************************/
function loadConfig () {
global $domain, $base, $ldaphost, $homelocation, $useLisGroup,
$groupbase, $authbase, $hostbase, $netgroupbase,
$automountbase, $variablesbase, $uname_maxlen,
$groupprefix, $authprefix, $hostprefix, $netgroupprefix,
$automountprefix, $variablesprefix, $uname_prefix,
$minPwLength, $minPwUpper, $minPwLower, $minPwNumber,
$allowPwSet, $tlsRequire, $smarty_templ, $smarty_compile ;
$groupprefix = "ou=Group" ;
$hostprefix = "ou=Hosts" ;
$netgroupprefix = "ou=Netgroup" ;
$variablesprefix = "ou=variables" ;
$automountprefix = "ou=Automount" ;
$homelocation = "/home" ;
$minPwLength = 5 ;
$minPwUpper = 1 ;
$minPwLower = 1 ;
$minPwNumber = 1 ;
$uname_maxlen = 8 ;
$allowPwSet = false ;
$smarty_templ = realpath ("../templates") ;
$smarty_compile = "/var/spool/lwat" ;
$domain = 'example.net' ;
$ldaphost = "ldap";
$useLisGroup = false ;
$tlsRequire = true ;
@include_once ("/etc/lwat/config.php");
if (!isset ($base)) {
$base_array = split ('.', $domain) ;
$base = 'dc=' . $base_array[0] ;
for ($i = 1 ; $i < count($base_array) ; $i++)
$base .= ",dc=" . $base_array[$i] ;
}
if (!is_dir ($smarty_compile))
$smarty_compile = "/var/tmp" ;
if (!is_file ($smarty_templ . "/login.tpl"))
$smarty_templ = realpath ("../templates") ;
if (isset ($groupbase)) {
$groupprefix = NULL ;
} elseif (isset($groupprefix))
$groupbase = $groupprefix . "," . $base ;
else
$groupbase = $base ;
if ($useLisGroup) {
$authbase = NULL ;
$authprefix = NULL ;
} elseif (isset ($authbase)) {
$useLisGroup = false ;
$authprefix = NULL ;
} elseif (isset($authprefix))
$authbase = $authprefix . "," . $base ;
else
$authbase = $base ;
if (isset ($hostbase))
$hostprefix = NULL ;
elseif (isset($hostprefix))
$hostbase = $hostprefix . "," . $base ;
else
$hostbase = $base ;
if (isset ($netgroupbase))
$netgroupprefix = NULL ;
elseif (isset($netgroupprefix))
$netgroupbase = $netgroupprefix . "," . $base ;
else
$netgroupbase = $base ;
if (isset ($variablesbase))
$variablesprefix = NULL ;
elseif (isset($variablesprefix))
$variablesbase = $variablesprefix . "," . $base ;
else
$variablesbase = $base ;
if (isset ($automountbase))
$automountprefix = NULL ;
elseif (isset($automountprefix))
$automountbase = $automountprefix . "," . $base ;
else
$automountbase = $base ;
}
/****************************************************************************
* loadLocale - Checks for browser language and tries to load locale
************
* try to load locale from cookie
* if no locale is found, and there is a locale subfolder
* create array of locales found under locales subfolder
* fetch the languages the browser accepts
* try to match exactly and mostly the locales for browser and application
* if exact locale is found use it
* else if match locale is found, use it
* if locale to use is found, set cookie
* set textdomain to use for locales
* set application output to be UTF8
****************************************************************************/
function loadLocale () {
if (isset ($_COOKIE['locale']))
$found_locale = $_COOKIE['locale'] ;
if (!isset($found_locale) && is_dir ('../locales')) {
$handle = @opendir ('../locales') ;
$all_locales = array () ;
while (false !== ($file = readdir ($handle))) {
if (is_dir ('../locales/' . $file . '/LC_MESSAGES')) {
$all_locales = array_merge ($all_locales, array ($file)) ;
}
}
closedir ($handle) ;
$lang_accept = array () ;
$lang_accept = explode (",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
for ($i = 0 ; $i < count ($lang_accept) ; $i++ ) {
$lang_accept[$i] = split(";", $lang_accept[$i]) ;
$lang_accept[$i] = $lang_accept[$i][0] ;
}
if (!empty($lang_accept[0]))
foreach ($lang_accept as $lang) {
if (!isset ($locale_exact)) {
foreach ($all_locales as $locales) {
if ($locales == $lang)
$locale_exact = $lang ;
elseif (!isset ($locale_match)) {
if (strpos ($locales, $lang) === 0)
$locale_match = $locales ;
}
}
}
}
if (isset ($locale_exact))
$found_locale=$locale_exact ;
elseif (isset ($locale_match))
$found_locale=$locale_match ;
if (isset ($found_locale))
setcookie ( 'locale', $found_locale) ;
unset ($all_locales, $lang_accept, $locale_match, $locale_exact, $lang, $locales) ;
}
if (isset ($found_locale)) {
$locale = setlocale (LC_ALL, $found_locale) ;
if (empty($locale))
setlocale (LC_ALL, $found_locale . ".UTF8");
bindtextdomain ("lwat", "../locales/");
bind_textdomain_codeset ("lwat", "UTF-8");
textdomain ("lwat");
}
header('Content-Type: text/html; charset=UTF-8') ;
}
/****************************************************************************
* xorstring - xors a string, to either crypt or decrypt data
*****************
* Arguments:
* key - key to use when encrypting or decrypting data
* xor - Data to xor, either clear text, or previously encrypted
* Returns:
* either encrypted or decrypted string
*****************
* if no key
* return nothing
* perform an xor with every character in string to be encrupted/decrypted
* with the correspondent charcater in key, repeat key if necesarry
* if at the end of a keyindex (assume decrypting)
* find first occurence of chr 0
* return string up to chr 0
* while not end of keyindex
* add with the rest of the key
* return encrypted string
****************************************************************************/
function xorstring ($key, $xor) {
$keylen=strlen ($key) ;
if (! $keylen) return "" ;
$newstr="" ;
$index=0 ;
$keyindex = $index ;
while ($index < strlen ($xor)) {
$newstr .= chr(ord($xor[$index]) ^ ord ($key[$keyindex])) ;
$index ++ ;
$keyindex= $index % $keylen ;
}
if ($keyindex == 0) {
$last=strpos ($newstr, chr(0));
if ($last === false) {
return $newstr ;
}
return(substr ($newstr, 0, $last)) ;
}
while ($keyindex != 0) {
$newstr .= $key[$keyindex] ;
$index ++ ;
$keyindex= $index % $keylen ;
}
return ($newstr) ;
}
/****************************************************************************
* readKey - Decodes data posted through the web-browser
*****************
* Arguments:
* key - which posted data to read
* Returns:
* the trimmed and stripped value of the data read
*****************
* Lookup data in posted array, trim, and remove clean data
****************************************************************************/
function readKey ($key) {
if (isset ($_POST[$key]))
return htmlspecialchars(trim($_POST[$key])) ;
return "" ;
}
/****************************************************************************
* debug - Displays data top debug through development
*****************
* Arguments:
* mixed - Data to display (array is preferred
*****************
* Display as preformatted code
****************************************************************************/
function debug ($mixed) {
echo "<pre>\n" ;
print_r ($mixed);
echo "\n</pre>\n" ;
}
/****************************************************************************
* pwgen - generates a random password
*****************
* Returns:
* a password that should be easy to say, but hard to guess
*****************
* First define consonants and vowels
* select random characters, 2 set of three
* Add a random number between 10 and 99
****************************************************************************/
function pwgen(){
$pw = '';
$c = 'bcdfghjkmnprstvwzBCDFGHJKLMNPQRSTVW'; //consonants except hard to speak ones
$v = 'aeiouAEU'; //vowels
$a = $c.$v; //both
//use two syllables...
for($i=0;$i < 2; $i++){
$pw .= $c[rand(0, strlen($c)-1)];
$pw .= $v[rand(0, strlen($v)-1)];
$pw .= $a[rand(0, strlen($a)-1)];
}
//... and add a nice number
$pw .= rand(10,99);
return $pw;
}
/****************************************************************************
* cryptgen - generates a crypted password from a given password,
* ready to be stored in ldap
*****************
* Arguments:
* clear - the clear text password
* Returns:
* a crypted password
*****************
* First prepare a salt using md5sum of random data
* Return base64 encoded sha1 encrypted password
****************************************************************************/
function cryptgen($clear){
//prepare a salt
$salt = md5(uniqid(rand(), true));
$salt=substr($salt,0,4);
return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
}
/****************************************************************************
* getnextid - fetch (and update) the next id to be used. This is
* stored in ldap under ou=variables
*****************
* Arguments
* connect - the ldap connection
* Returns:
* the next ID to be used
*****************
* Search for a nextID under ou=Variables
* Loop
* minimum nextID should be 10000
* if nextID > 59999
* if already looped
* Die with an error message
* else
* set looped
* restart from 10000
* search ldap for found gidNumber or uidNumber
* increase NextID if found
* until free uidNumber and gidNumber is found
* build new ID to be stored in ldap
* if add newID to ldap with success
* delete old nextID
* rename newID nextID
* return nextID
* die with error message
****************************************************************************/
function getnextid ($connect) {
global $variablesbase, $base ;
$looped = false ;
$nextID=0 ;
$want= array ("gidNumber", "uidNumber");
$filter = "(&(gidNumber=*)(cn=nextID))" ;
$result= @ldap_search ($connect, "ou=Variables," . $base, $filter, $want);
if ($result) {
$entries = ldap_get_entries ($connect, $result) ;
if ($entries["count"])
$nextID=$entries[0]["gidnumber"][0] ;
}
do {
if ($nextID < 10000) $nextID=10000 ;
else if ($nextID > 59999) {
if ($looped) {
die ('Sorry, all user id\'s between 10000 and 59999 seems to have been taken') ;
} else {
$looped = true ;
$nextID=10000 ;
}
}
$filter = "(&(|(gidNumber=$nextID)(uidNumber=$nextID))(!(cn=nextID)))" ;
$result = @ldap_search ($connect, $base, $filter, $want);
$entries = @ldap_get_entries ($connect, $result) ;
if ($entries["count"] > 0) $nextID++ ;
} while ($entries["count"]) ;
$info=array () ;
$info["objectClass"] = array ("top", "posixGroup") ;
$info["gidnumber"] = $nextID + 1 ;
$info["cn"] = "newID" ;
if (@ldap_add ($connect,"cn=newID," . $variablesbase,$info)) {
@ldap_delete ($connect,"cn=nextID," . $variablesbase) ;
@ldap_rename ($connect,"cn=newID," . $variablesbase, "cn=nextID", $variablesbase, true) ;
return $nextID ;
}
$ldaperr = ldap_errno ($connect) ;
switch ($ldaperr) {
case 50:
die (_("Sorry, you are not allowed to add users")) ;
break ;
default:
reportLdapError ($ldaperr, "getnextid") ;
break ;
}
die ("<BR />" . _("Please report a bug to the lwat developers")) ;
}
/****************************************************************************
* get_sn - parses a full name, and fetches the surname
*****************
* Arguments:
* newname - name to extract surname from
* Returns:
* surname
*****************
* split fullname by spaces
* find the last name
* return the last name
****************************************************************************/
function get_sn ($newname) {
$sn="" ;
$allnames = explode (" ", $newname) ;
foreach ($allnames as $name) {
$sn=$name ;
}
return $sn;
}
/****************************************************************************
* chk_username - Checks if a given username is already taken
*****************
* Arguments:
* connect - ldap connection
* username - Username to check
* excludes - username not to use (maybe they are already checked,
* and prepared for other users in an import)
* Returns:
* false if found, true if username can be used
*****************
* search ldap for username or groupName
* if found
* return false
* search trough username which should be excluded
* if found, return false
* return true (actually, return username)
****************************************************************************/
function chk_username ($connect, $username, $excludes) {
global $base ;
$filter = "(|(uid=$username)(cn=$username))" ;
$result= ldap_search ($connect, $base, $filter);
$entries = ldap_get_entries ($connect, $result) ;
if ($entries["count"])
return "" ;
if (is_array($excludes)) {
$result = in_array ($username, $excludes) ;
if ($result)
return "" ;
}
return $username ;
}
/****************************************************************************
* get_username - generates a username from a fullname
*****************
* Arguments:
* connect - ldap connection
* newname - the fullname to generate a new name from
* excludes - username not to be used (already prepared to imported?)
* Returns:
* new username generated
*****************
* try to detect encoding
* found encoding ISO-8859-1
* no need to convert characters
* default
* convert from found charset to ISO-8859-1
* Look through found characters for known characters > chr 128
* convert them to A, C, E, I, N, O, U, Y, P (or lowercase variants)
* convert everything to lower chars
* split the names based on spaces and other separators
* find first and last name
* try taking 3 chars from first and last name
* check found name against existing
* if not found return name
* loop while vowels
* loop while vowels
* take 1, then 2, then 3... from each name but firstname
* trim from firstname till firstname and X characters from other
* names is 8 chars
* if username not used, return name
* Remove a vowel from "restnames"
* Remove a vovel from first name
* Try to use 3 from first + 3 from last and add 00-99
* if username not used return username
* finally give up :(
****************************************************************************/
function get_username ($connect, $newname, $excludes = NULL) {
global $base, $uname_prefix ;
$charset = mb_detect_encoding ($newname, 'UTF-8, ISO-8859-1') ;
switch ($charset) {
case 'ISO-8859-1':
$basename = $newname ;
break ;
default:
$basename = mb_convert_encoding ($newname, 'ISO-8859-1', $charset);
break ;
}
for ($i=0 ; $i < strlen($basename); $i++) {
switch (ord($basename[$i])) {
case 192: case 193: case 194: case 195: case 196: case 197:
$basename[$i] = "A" ;
break ;
case 199:
$basename[$i] = "C" ;
break ;
case 198: case 200: case 201: case 202: case 203:
$basename[$i] = "E" ;
break ;
case 204: case 205: case 206: case 207:
$basename[$i] = "I" ;
break ;
case 209 :
$basename[$i] = "N" ;
break ;
case 208: case 210: case 211: case 212: case 213: case 214: case 216 :
$basename[$i] = "O" ;
break ;
case 217: case 218: case 219: case 220 :
$basename[$i] = "U" ;
break ;
case 221 :
$basename[$i] = "Y" ;
break ;
case 222 :
$basename[$i] = "P" ;
break ;
case 223 :
$basename[$i] = "I" ;
break ;
case 224: case 225: case 226: case 227: case 228: case 229 :
$basename[$i] = "a" ;
break ;
case 231 :
$basename[$i] = "c" ;
break ;
case 230: case 232: case 233: case 234: case 235 :
$basename[$i] = "e" ;
break ;
case 236: case 237: case 238: case 239 :
$basename[$i] = "i" ;
break ;
case 241 :
$basename[$i] = "n" ;
break ;
case 240: case 242: case 243: case 244: case 245: case 246: case 248 :
$basename[$i] = "o" ;
break ;
case 249: case 250: case 251: case 252 :
$basename[$i] = "u" ;
break ;
case 253: case 255 :
$basename[$i] = "y" ;
break ;
case 254 :
$basename[$i] = "p" ;
break ;
default:
if ($basename[$i] >= "0" and $basename[$i] <= "9")
break ;
if ($basename[$i] >= "A" and $basename[$i] <= "Z")
break ;
if ($basename[$i] >= "a" and $basename[$i] <= "z")
break ;
$basename[$i] = " " ;
break ;
}
}
$basename = trim (strtolower ($basename)) ;
$allnames = split (" +", $basename) ;
$firstname = $allnames[0] ;
foreach ($allnames as $name)
if (!empty ($name)) $lastname=$name ;
$bigname = substr ($firstname, 0,3) . substr ($lastname, 0,3) ;
$username = chk_username ($connect, $uname_prefix . $bigname, $excludes);
if (!empty($username))
return $username ;
$loop="aeiouy" ;
while (ereg ("[aeiouy]", $loop)) {
$restname="" ;
for ($i=1 ; $i < (count($allnames)); $i++)
$restname .= $allnames[$i] . " " ;
while (ereg ("[aeiouy]", $loop)) {
for ($count=1 ; $count <= 6 ; $count++ ) {
$addname="" ;
foreach (explode (" ", $restname) as $name)
$addname .= substr ($name, 0, $count);
while (strlen ($addname) > 6)
$addname=substr($addname, $count);
$username= chk_username($connect, $uname_prefix . substr($firstname,0,8 - strlen($addname)) . $addname, $excludes) ;
if (!empty($username))
return $username ;
}
$length=strlen($restname);
$loop="" ;
while ($length--) {
switch ($restname[$length]) {
case "a": case "e": case "i": case "o": case "u": case "y":
$loop=$restname[$length] ;
$restname=substr($restname, 0,$length) . substr($restname, $length + 1) ;
$length = 0 ;
break ;
}
}
}
$length=strlen($firstname);
$loop="" ;
while ($length--) {
switch ($firstname[$length]) {
case "a": case "e": case "i": case "o": case "u": case "y":
$loop=$firstname[$length] ;
$firstname=substr($firstname, 0,$length) . substr($firstname, $length + 1) ;
$length = 0 ;
break ;
}
}
}
for ($i=0 ; $i < 100 ; $i++) {
$username = chk_username ($connect,
$uname_prefix . sprintf ("%s%02d", $bigname, $i),
$excludes) ;
if (! empty($username)) return $username ;
}
echo "Sorry, I'm unable to generate a unique username for $newname<BR>";
return "" ;
}
/****************************************************************************
* get_givenName - parses a fullname, and extract a givenName
*****************
* Arguments:
* newname - The full name
* Returns:
* The given name (everything but the last name)
*****************
* for each name in full name
* add previous name to the given name
* remember the last name
* if no given name is found
* use the last name
* return given name
****************************************************************************/
function get_givenName ($newname) {
$last="" ;
foreach (explode (" ", $newname) as $value) {
$givenName .= $last ;
$last = "$value" . " " ;
}
if (! $givenName) $givenName=$last ;
return $givenName ;
}
/****************************************************************************
* get_sambasid - looks up the sambasid to be used.
*****************
* Arguments:
* connect - ldap connection
* userid - userid to create sambaSid for
* Returns:
* the samba sid as a string
*****************
* look up a sambaDomain in ldap
* check number of entries
* 0: warn that there is none
* 1: continue
* *: warn that there is to many
****************************************************************************/
function get_sambasid ($connect, $userid) {
global $base ;
$want= array ("sambasid");
$filter = "(objectClass=sambaDomain)" ;
$result = @ldap_search ($connect, $base, $filter, $want);
$entries = @ldap_get_entries ($connect, $result) ;
switch ($entries["count"]) {
case 0:
die (_("Sorry, can't find no sambaDomain in your ldap"). "<BR>") ;
case 1: break ;
default:
die (_("Sorry, there is more than one sambaDomain in your ldap server, and this version of lwat only supports one"). "<BR>") ;
}
$sambaSID=$entries[0]["sambasid"][0] . sprintf("-%d", $userid * 2 + 1000) ;
return $sambaSID ;
}
/****************************************************************************
* ldapAddUser - Adds a user into ldap
*****************
* Arguments:
* ldap - ldap connection
* cn - Common name of the new user
* template - Template to use to create user
* username - The username
* userpw - password
* groups - list of groups (in addition to those from the template)
* to add the user into
* Returns:
* returns true if the user was created, false otherwise
*****************
* parse template file
* fetch surname from username
* fetch the next userid to use
* check if special lis schema should be used when creatign a personal group
* Set up to replace username, basem domain and surname with real values
* Parse template, to build a complete ldap object
* ou: this is the objectunit which the object is stored under
* groups: add these groups from the template to the list of groups
* for the user
* objectClass: this must be added as an array
* *) the rest is just added as normal key => value stuff
* if samba Account
* Add samba Info
* Add the user
* report any error
* if lisGroup are to be used, set groupbase
* add personal group
* for each group the user should be added into
* if unable to add
* remember
* if not unable to add to any group
* return success
* Remove all groups we could not add the user into
* return success
****************************************************************************/
function ldapAddUser ($ldap, $cn, $template, $username, $userpw, $groups) {
global $groupbase, $base, $domain, $useLisGroup ;
$templates = parse_ini_file ('/etc/lwat/admin.ini', true) ;
$template = $templates[$template] ;
$sn = get_sn ($cn) ;
$userid = getnextid ($ldap) ;
$userldif['uidNumber'] = $userid ;
$userldif['gidNumber'] = $userid ;
$userldif['uid'] = $username ;
$userldif['cn'] = $cn ;
$userldif['userPassword'] = cryptgen($userpw) ;
if ($useLisGroup === true) {
$groupldif["objectClass"] = array ("top", "posixGroup", 'lisGroup') ;
$groupldif["groupType"] = "private" ;
} else
$groupldif["objectClass"] = array ("top", "posixGroup") ;
$groupldif["cn"] = $username ;
$groupldif["gidNumber"] = $userid ;
$groupldif["description"] = "$cn personal group" ;
$replace=array("%username%", "%base%", "%domain%", "%sn%") ;
$replacewith =array($username, $base, $domain, $sn) ;
foreach ($template as $key => $value) {
$value = str_replace ($replace, $replacewith, $value) ;
switch ($key) {
case "ou":
$ou=$value ;
break ;
case "groups":
if (is_array ($groups))
$groups = array_merge ($groups, explode (" ", $value)) ;
else
$groups = explode (" ", $value) ;
break ;
case "objectClass":
$userldif['objectClass'] = explode (" ", $value);
break ;
default:
$userldif[$key] = $value ;
break ;
}
}
if (in_array ('sambaSamAccount',$userldif['objectClass']))
$userldif = (array_merge($userldif, sambaAddInfo ($ldap, $userldif, $userpw))) ;
if (!@ldap_add($ldap, "uid=" . $username . "," . $ou, $userldif)) {
$ldaperr = ldap_errno ($ldap) ;
switch ($ldaperr) {
case 68:
die (sprintf (_("The username %s already exists"), $username)) ;
default:
reportLdapError (ldap_errno ($ldap), "Add user") ;
break ;
}
return false;
}
if ($useLisGroup) $ou=$groupbase ;
if (!@ldap_add($ldap, "cn=" . $username . "," . $ou, $groupldif)) {
printf (_("Failed to add personal group for ") . $cn . "<BR>") ;
}
$nogroup = array () ;
foreach ($groups as $group) {
$filter="(&(objectClass=posixGroup)(cn=" . $group . "))";
$want = array ('gidNumber');
$result = ldap_search($ldap, $groupbase, $filter, $want);
$entries = ldap_get_entries ($ldap, $result);
$gid= $entries[0]['gidnumber'][0] ;
if (!userAddGroup ($ldap, $username, $gid))
$nogroup[] = $group ;
}
if (empty($nogroup)) return true ;
foreach ($nogroup as $group) {
$pos = in_array ($group, $groups) ;
if (isset ($pos))
array_splice ($groups, $pos - 1 , 1) ;
}
return true ;
}
/****************************************************************************
* sambaAddInfo - Adds samba information for a user
*****************
* Arguments:
* Returns:
*****************
* FIXME describe this function (and other not described functions in this file
****************************************************************************/
function sambaAddInfo ($ldap, $userldif, $userpw) {
$sambahash = new smbHash () ;
$sambaldif = array () ;
$sambaldif['sambaSID'] = get_sambasid ($ldap, $userldif['uidNumber']) ;
$sambaldif["sambaAcctFlags"] = "[U ]" ;
$sambaldif["sambaLMPassword"] = $sambahash->lmhash($userpw) ;
$sambaldif["sambaNTPassword"] = $sambahash->nthash($userpw) ;
return $sambaldif ;
}
/****************************************************************************
* userAddGroup - Add a user into a group
*****************
* Arguments:
* Returns:
*****************
* FIXME describe this function (and other not described functions in this file
****************************************************************************/
function userAddGroup ($ldap, $uid, $gid) {
global $groupbase, $base ;
$filter="(&(objectClass=posixGroup)(gidNumber=" . $gid . "))";
$want = array ('cn');
$searchbase=$groupbase ;
$result = ldap_search($ldap, $searchbase, $filter, $want);
$entries = ldap_get_entries ($ldap, $result);
$groupdn=$entries[0]["dn"] ;
$cn=$entries[0]["cn"][0] ;
$change = array ();
$change["memberUid"][] = $uid ;
if (!@ldap_mod_add($ldap, $groupdn, $change))
return false ;
$filter="(&(member=*)(cn=" . $cn . "))";
$result = ldap_search($ldap, $base, $filter, $want);
$entries = ldap_get_entries ($ldap, $result);
$groupdn=$entries[0]["dn"] ;
$change = array ();
if ($entries[count]) {
$want = array ();
$filter="(&(objectClass=posixAccount)(uid=" . $uid ."))";
$result = ldap_search($ldap, $base, $filter, $want);
$entries = ldap_get_entries ($ldap, $result) ;
$change["member"][] = $entries[0]["dn"] ;
@ldap_mod_add($ldap, $groupdn, $change) ;
}
return true ;
}
?>
|