xref: /dokuwiki/inc/auth.php (revision a6858c6a90527664406b82e32fcf457628700df1)
1<?php
2/**
3 * Authentication library
4 *
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
7 *
8 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author     Andreas Gohr <andi@splitbrain.org>
10 */
11
12  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
13  require_once(DOKU_INC.'inc/common.php');
14  require_once(DOKU_INC.'inc/io.php');
15
16	global $conf;
17
18  if($conf['useacl']){
19    require_once(DOKU_INC.'inc/blowfish.php');
20    require_once(DOKU_INC.'inc/mail.php');
21
22    global $auth;
23
24    // load the the backend auth functions and instantiate the auth object
25    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
26      require_once(DOKU_INC.'inc/auth/basic.class.php');
27      require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
28
29      $auth_class = "auth_".$conf['authtype'];
30      if (class_exists($auth_class)) {
31        $auth = new $auth_class();
32        if ($auth->success == false) {
33          unset($auth);
34          msg($lang['authtempfail'], -1);
35
36          // turn acl config setting off for the rest of this page
37          $conf['useacl'] = 0;
38        }
39      } else {
40        nice_die($lang['authmodfailed']);
41      }
42    } else {
43      nice_die($lang['authmodfailed']);
44    }
45  }
46
47  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5($conf['title']));
48
49  // some ACL level defines
50  define('AUTH_NONE',0);
51  define('AUTH_READ',1);
52  define('AUTH_EDIT',2);
53  define('AUTH_CREATE',4);
54  define('AUTH_UPLOAD',8);
55  define('AUTH_DELETE',16);
56  define('AUTH_ADMIN',255);
57
58  // do the login either by cookie or provided credentials
59  if($conf['useacl']){
60    if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
61    if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
62    if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
63
64    // if no credentials were given try to use HTTP auth (for SSO)
65    if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
66      $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
67      $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
68    }
69
70    // external trust mechanism in place?
71    if(!is_null($auth) && $auth->canDo('external')){
72      $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
73    }else{
74      auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
75    }
76
77    //load ACL into a global array
78    if(is_readable(DOKU_CONF.'acl.auth.php')){
79      $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
80    }else{
81      $AUTH_ACL = array();
82    }
83  }
84
85/**
86 * This tries to login the user based on the sent auth credentials
87 *
88 * The authentication works like this: if a username was given
89 * a new login is assumed and user/password are checked. If they
90 * are correct the password is encrypted with blowfish and stored
91 * together with the username in a cookie - the same info is stored
92 * in the session, too. Additonally a browserID is stored in the
93 * session.
94 *
95 * If no username was given the cookie is checked: if the username,
96 * crypted password and browserID match between session and cookie
97 * no further testing is done and the user is accepted
98 *
99 * If a cookie was found but no session info was availabe the
100 * blowfish encrypted password from the cookie is decrypted and
101 * together with username rechecked by calling this function again.
102 *
103 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
104 * are set.
105 *
106 * @author  Andreas Gohr <andi@splitbrain.org>
107 *
108 * @param   string  $user    Username
109 * @param   string  $pass    Cleartext Password
110 * @param   bool    $sticky  Cookie should not expire
111 * @return  bool             true on successful auth
112*/
113function auth_login($user,$pass,$sticky=false){
114  global $USERINFO;
115  global $conf;
116  global $lang;
117  global $auth;
118  $sticky ? $sticky = true : $sticky = false; //sanity check
119
120  if(!empty($user)){
121    //usual login
122    if ($auth->checkPass($user,$pass)){
123      // make logininfo globally available
124      $_SERVER['REMOTE_USER'] = $user;
125      $USERINFO = $auth->getUserData($user); //FIXME move all references to session
126
127      // set cookie
128      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
129      $cookie = base64_encode("$user|$sticky|$pass");
130      if($sticky) $time = time()+60*60*24*365; //one year
131      setcookie(DOKU_COOKIE,$cookie,$time,'/');
132
133      // set session
134      $_SESSION[$conf['title']]['auth']['user'] = $user;
135      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
136      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
137      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
138      return true;
139    }else{
140      //invalid credentials - log off
141      msg($lang['badlogin'],-1);
142      auth_logoff();
143      return false;
144    }
145  }else{
146    // read cookie information
147    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
148    list($user,$sticky,$pass) = split('\|',$cookie,3);
149    // get session info
150    $session = $_SESSION[$conf['title']]['auth'];
151
152    if($user && $pass){
153      // we got a cookie - see if we can trust it
154      if(isset($session) &&
155        ($session['user'] == $user) &&
156        ($session['pass'] == $pass) &&  //still crypted
157        ($session['buid'] == auth_browseruid()) ){
158        // he has session, cookie and browser right - let him in
159        $_SERVER['REMOTE_USER'] = $user;
160        $USERINFO = $session['info']; //FIXME move all references to session
161        return true;
162      }
163      // no we don't trust it yet - recheck pass
164      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
165      return auth_login($user,$pass,$sticky);
166    }
167  }
168  //just to be sure
169  auth_logoff();
170  return false;
171}
172
173/**
174 * Builds a pseudo UID from browser and IP data
175 *
176 * This is neither unique nor unfakable - still it adds some
177 * security. Using the first part of the IP makes sure
178 * proxy farms like AOLs are stil okay.
179 *
180 * @author  Andreas Gohr <andi@splitbrain.org>
181 *
182 * @return  string  a MD5 sum of various browser headers
183 */
184function auth_browseruid(){
185  $uid  = '';
186  $uid .= $_SERVER['HTTP_USER_AGENT'];
187  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
188  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
189  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
190  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
191  return md5($uid);
192}
193
194/**
195 * Creates a random key to encrypt the password in cookies
196 *
197 * This function tries to read the password for encrypting
198 * cookies from $conf['metadir'].'/_htcookiesalt'
199 * if no such file is found a random key is created and
200 * and stored in this file.
201 *
202 * @author  Andreas Gohr <andi@splitbrain.org>
203 *
204 * @return  string
205 */
206function auth_cookiesalt(){
207  global $conf;
208  $file = $conf['metadir'].'/_htcookiesalt';
209  $salt = io_readFile($file);
210  if(empty($salt)){
211    $salt = uniqid(rand(),true);
212    io_saveFile($file,$salt);
213  }
214  return $salt;
215}
216
217/**
218 * This clears all authenticationdata and thus log the user
219 * off
220 *
221 * @author  Andreas Gohr <andi@splitbrain.org>
222 */
223function auth_logoff(){
224  global $conf;
225  global $USERINFO;
226  global $INFO, $ID;
227  global $auth;
228
229  if(isset($_SESSION[$conf['title']]['auth']['user']))
230    unset($_SESSION[$conf['title']]['auth']['user']);
231  if(isset($_SESSION[$conf['title']]['auth']['pass']))
232    unset($_SESSION[$conf['title']]['auth']['pass']);
233  if(isset($_SESSION[$conf['title']]['auth']['info']))
234    unset($_SESSION[$conf['title']]['auth']['info']);
235  if(isset($_SERVER['REMOTE_USER']))
236    unset($_SERVER['REMOTE_USER']);
237  $USERINFO=null; //FIXME
238  setcookie(DOKU_COOKIE,'',time()-600000,'/');
239
240  if($auth && $auth->canDo('logoff')){
241    $auth->logOff();
242  }
243}
244
245/**
246 * Convinience function for auth_aclcheck()
247 *
248 * This checks the permissions for the current user
249 *
250 * @author  Andreas Gohr <andi@splitbrain.org>
251 *
252 * @param  string  $id  page ID
253 * @return int          permission level
254 */
255function auth_quickaclcheck($id){
256  global $conf;
257  global $USERINFO;
258  # if no ACL is used always return upload rights
259  if(!$conf['useacl']) return AUTH_UPLOAD;
260  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
261}
262
263/**
264 * Returns the maximum rights a user has for
265 * the given ID or its namespace
266 *
267 * @author  Andreas Gohr <andi@splitbrain.org>
268 *
269 * @param  string  $id     page ID
270 * @param  string  $user   Username
271 * @param  array   $groups Array of groups the user is in
272 * @return int             permission level
273 */
274function auth_aclcheck($id,$user,$groups){
275  global $conf;
276  global $AUTH_ACL;
277
278  # if no ACL is used always return upload rights
279  if(!$conf['useacl']) return AUTH_UPLOAD;
280
281  $user = auth_nameencode($user);
282
283  //if user is superuser return 255 (acl_admin)
284  if(auth_nameencode($conf['superuser']) == $user) { return AUTH_ADMIN; }
285
286  //make sure groups is an array
287  if(!is_array($groups)) $groups = array();
288
289  //prepend groups with @ and nameencode
290  $cnt = count($groups);
291  for($i=0; $i<$cnt; $i++){
292    $groups[$i] = '@'.auth_nameencode($groups[$i]);
293  }
294  //if user is in superuser group return 255 (acl_admin)
295  if(in_array(auth_nameencode($conf['superuser'],true), $groups)) { return AUTH_ADMIN; }
296
297  $ns    = getNS($id);
298  $perm  = -1;
299
300  if($user){
301    //add ALL group
302    $groups[] = '@ALL';
303    //add User
304    $groups[] = $user;
305    //build regexp
306    $regexp   = join('|',$groups);
307  }else{
308    $regexp = '@ALL';
309  }
310
311  //check exact match first
312  $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
313  if(count($matches)){
314    foreach($matches as $match){
315      $match = preg_replace('/#.*$/','',$match); //ignore comments
316      $acl   = preg_split('/\s+/',$match);
317      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
318      if($acl[2] > $perm){
319        $perm = $acl[2];
320      }
321    }
322    if($perm > -1){
323      //we had a match - return it
324      return $perm;
325    }
326  }
327
328  //still here? do the namespace checks
329  if($ns){
330    $path = $ns.':\*';
331  }else{
332    $path = '\*'; //root document
333  }
334
335  do{
336    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
337    if(count($matches)){
338      foreach($matches as $match){
339        $match = preg_replace('/#.*$/','',$match); //ignore comments
340        $acl   = preg_split('/\s+/',$match);
341        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
342        if($acl[2] > $perm){
343          $perm = $acl[2];
344        }
345      }
346      //we had a match - return it
347      return $perm;
348    }
349
350    //get next higher namespace
351    $ns   = getNS($ns);
352
353    if($path != '\*'){
354      $path = $ns.':\*';
355      if($path == ':\*') $path = '\*';
356    }else{
357      //we did this already
358      //looks like there is something wrong with the ACL
359      //break here
360      msg('No ACL setup yet! Denying access to everyone.');
361      return AUTH_NONE;
362    }
363  }while(1); //this should never loop endless
364
365  //still here? return no permissions
366  return AUTH_NONE;
367}
368
369/**
370 * Encode ASCII special chars
371 *
372 * Some auth backends allow special chars in their user and groupnames
373 * The special chars are encoded with this function. Only ASCII chars
374 * are encoded UTF-8 multibyte are left as is (different from usual
375 * urlencoding!).
376 *
377 * Decoding can be done with rawurldecode
378 *
379 * @author Andreas Gohr <gohr@cosmocode.de>
380 * @see rawurldecode()
381 */
382function auth_nameencode($name,$skip_group=false){
383  if($skip_group && $name{0} =='@'){
384    return '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
385                            "'%'.dechex(ord('\\1'))",substr($name,1));
386  }else{
387    return preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
388                        "'%'.dechex(ord('\\1'))",$name);
389  }
390}
391
392/**
393 * Create a pronouncable password
394 *
395 * @author  Andreas Gohr <andi@splitbrain.org>
396 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
397 *
398 * @return string  pronouncable password
399 */
400function auth_pwgen(){
401  $pw = '';
402  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
403  $v  = 'aeiou';              //vowels
404  $a  = $c.$v;                //both
405
406  //use two syllables...
407  for($i=0;$i < 2; $i++){
408    $pw .= $c[rand(0, strlen($c)-1)];
409    $pw .= $v[rand(0, strlen($v)-1)];
410    $pw .= $a[rand(0, strlen($a)-1)];
411  }
412  //... and add a nice number
413  $pw .= rand(10,99);
414
415  return $pw;
416}
417
418/**
419 * Sends a password to the given user
420 *
421 * @author  Andreas Gohr <andi@splitbrain.org>
422 *
423 * @return bool  true on success
424 */
425function auth_sendPassword($user,$password){
426  global $conf;
427  global $lang;
428  global $auth;
429
430  $hdrs  = '';
431  $userinfo = $auth->getUserData($user);
432
433  if(!$userinfo['mail']) return false;
434
435  $text = rawLocale('password');
436  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
437  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
438  $text = str_replace('@LOGIN@',$user,$text);
439  $text = str_replace('@PASSWORD@',$password,$text);
440  $text = str_replace('@TITLE@',$conf['title'],$text);
441
442  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
443                   $lang['regpwmail'],
444                   $text,
445                   $conf['mailfrom']);
446}
447
448/**
449 * Register a new user
450 *
451 * This registers a new user - Data is read directly from $_POST
452 *
453 * @author  Andreas Gohr <andi@splitbrain.org>
454 *
455 * @return bool  true on success, false on any error
456 */
457function register(){
458  global $lang;
459  global $conf;
460  global $auth;
461
462  if(!$_POST['save']) return false;
463  if(!$auth->canDo('addUser')) return false;
464
465  //clean username
466  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
467  $_POST['login'] = cleanID($_POST['login']);
468  //clean fullname and email
469  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['fullname']));
470  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['email']));
471
472  if( empty($_POST['login']) ||
473      empty($_POST['fullname']) ||
474      empty($_POST['email']) ){
475    msg($lang['regmissing'],-1);
476    return false;
477  }
478
479  if ($conf['autopasswd']) {
480    $pass = auth_pwgen();                // automatically generate password
481  } elseif (empty($_POST['pass']) ||
482            empty($_POST['passchk'])) {
483    msg($lang['regmissing'], -1);        // complain about missing passwords
484    return false;
485  } elseif ($_POST['pass'] != $_POST['passchk']) {
486    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
487    return false;
488  } else {
489    $pass = $_POST['pass'];              // accept checked and valid password
490  }
491
492  //check mail
493  if(!mail_isvalid($_POST['email'])){
494    msg($lang['regbadmail'],-1);
495    return false;
496  }
497
498  //okay try to create the user
499  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
500    msg($lang['reguexists'],-1);
501    return false;
502  }
503
504  if (!$conf['autopasswd']) {
505    msg($lang['regsuccess2'],1);
506    notify('', 'register', '', $_POST['login'], false);
507    return true;
508  }
509
510  // autogenerated password? then send him the password
511  if (auth_sendPassword($_POST['login'],$pass)){
512    msg($lang['regsuccess'],1);
513    notify('', 'register', '', $_POST['login'], false);
514    return true;
515  }else{
516    msg($lang['regmailfail'],-1);
517    return false;
518  }
519}
520
521/**
522 * Update user profile
523 *
524 * @author    Christopher Smith <chris@jalakai.co.uk>
525 */
526function updateprofile() {
527  global $conf;
528  global $INFO;
529  global $lang;
530  global $auth;
531
532  if(!$_POST['save']) return false;
533
534  // should not be able to get here without Profile being possible...
535  if(!$auth->canDo('Profile')) {
536    msg($lang['profna'],-1);
537    return false;
538  }
539
540  if ($_POST['newpass'] != $_POST['passchk']) {
541    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
542    return false;
543  }
544
545  //clean fullname and email
546  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['fullname']));
547  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['email']));
548
549  if (empty($_POST['fullname']) || empty($_POST['email'])) {
550    msg($lang['profnoempty'],-1);
551    return false;
552  }
553
554  if (!mail_isvalid($_POST['email'])){
555    msg($lang['regbadmail'],-1);
556    return false;
557  }
558
559  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
560  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
561  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
562
563  if (!count($changes)) {
564    msg($lang['profnochange'], -1);
565    return false;
566  }
567
568  if ($conf['profileconfirm']) {
569      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
570      msg($lang['badlogin'],-1);
571      return false;
572    }
573  }
574
575  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
576}
577
578/**
579 * Send a  new password
580 *
581 * This function handles both phases of the password reset:
582 *
583 *   - handling the first request of password reset
584 *   - validating the password reset auth token
585 *
586 * @author Benoit Chesneau <benoit@bchesneau.info>
587 * @author Chris Smith <chris@jalakai.co.uk>
588 * @author Andreas Gohr <andi@splitbrain.org>
589 *
590 * @return bool true on success, false on any error
591*/
592function act_resendpwd(){
593    global $lang;
594    global $conf;
595    global $auth;
596
597    if(!actionOK('resendpwd')) return false;
598
599    // should not be able to get here without modPass being possible...
600    if(!$auth->canDo('modPass')) {
601        msg($lang['resendna'],-1);
602        return false;
603    }
604
605    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
606
607    if($token){
608        // we're in token phase
609
610        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
611        if(!@file_exists($tfile)){
612            msg($lang['resendpwdbadauth'],-1);
613            return false;
614        }
615        $user = io_readfile($tfile);
616        @unlink($tfile);
617        $userinfo = $auth->getUserData($user);
618        if(!$userinfo['mail']) {
619            msg($lang['resendpwdnouser'], -1);
620            return false;
621        }
622
623        $pass = auth_pwgen();
624        if (!$auth->modifyUser($user,array('pass' => $pass))) {
625            msg('error modifying user data',-1);
626            return false;
627        }
628
629        if (auth_sendPassword($user,$pass)) {
630            msg($lang['resendpwdsuccess'],1);
631        } else {
632            msg($lang['regmailfail'],-1);
633        }
634        return true;
635
636    } else {
637        // we're in request phase
638
639        if(!$_POST['save']) return false;
640
641        if (empty($_POST['login'])) {
642            msg($lang['resendpwdmissing'], -1);
643            return false;
644        } else {
645            $user = $_POST['login'];
646        }
647
648        $userinfo = $auth->getUserData($user);
649        if(!$userinfo['mail']) {
650            msg($lang['resendpwdnouser'], -1);
651            return false;
652        }
653
654        // generate auth token
655        $token = md5(auth_cookiesalt().$user); //secret but user based
656        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
657        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
658
659        io_saveFile($tfile,$user);
660
661        $text = rawLocale('pwconfirm');
662        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
663        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
664        $text = str_replace('@LOGIN@',$user,$text);
665        $text = str_replace('@TITLE@',$conf['title'],$text);
666        $text = str_replace('@CONFIRM@',$url,$text);
667
668        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
669                     $lang['regpwmail'],
670                     $text,
671                     $conf['mailfrom'])){
672            msg($lang['resendpwdconfirm'],1);
673        }else{
674            msg($lang['regmailfail'],-1);
675        }
676        return true;
677    }
678
679    return false; // never reached
680}
681
682/**
683 * Uses a regular expresion to check if a given mail address is valid
684 *
685 * May not be completly RFC conform!
686 *
687 * @link    http://www.webmasterworld.com/forum88/135.htm
688 *
689 * @param   string $email the address to check
690 * @return  bool          true if address is valid
691 */
692function isvalidemail($email){
693  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
694}
695
696/**
697 * Encrypts a password using the given method and salt
698 *
699 * If the selected method needs a salt and none was given, a random one
700 * is chosen.
701 *
702 * The following methods are understood:
703 *
704 *   smd5  - Salted MD5 hashing
705 *   md5   - Simple MD5 hashing
706 *   sha1  - SHA1 hashing
707 *   ssha  - Salted SHA1 hashing
708 *   crypt - Unix crypt
709 *   mysql - MySQL password (old method)
710 *   my411 - MySQL 4.1.1 password
711 *
712 * @author  Andreas Gohr <andi@splitbrain.org>
713 * @return  string  The crypted password
714 */
715function auth_cryptPassword($clear,$method='',$salt=''){
716  global $conf;
717  if(empty($method)) $method = $conf['passcrypt'];
718
719  //prepare a salt
720  if(empty($salt)) $salt = md5(uniqid(rand(), true));
721
722  switch(strtolower($method)){
723    case 'smd5':
724        return crypt($clear,'$1$'.substr($salt,0,8).'$');
725    case 'md5':
726      return md5($clear);
727    case 'sha1':
728      return sha1($clear);
729    case 'ssha':
730      $salt=substr($salt,0,4);
731      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
732    case 'crypt':
733      return crypt($clear,substr($salt,0,2));
734    case 'mysql':
735      //from http://www.php.net/mysql comment by <soren at byu dot edu>
736      $nr=0x50305735;
737      $nr2=0x12345671;
738      $add=7;
739      $charArr = preg_split("//", $clear);
740      foreach ($charArr as $char) {
741        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
742        $charVal = ord($char);
743        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
744        $nr2 += ($nr2 << 8) ^ $nr;
745        $add += $charVal;
746      }
747      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
748    case 'my411':
749      return '*'.sha1(pack("H*", sha1($clear)));
750    default:
751      msg("Unsupported crypt method $method",-1);
752  }
753}
754
755/**
756 * Verifies a cleartext password against a crypted hash
757 *
758 * The method and salt used for the crypted hash is determined automatically
759 * then the clear text password is crypted using the same method. If both hashs
760 * match true is is returned else false
761 *
762 * @author  Andreas Gohr <andi@splitbrain.org>
763 * @return  bool
764 */
765function auth_verifyPassword($clear,$crypt){
766  $method='';
767  $salt='';
768
769  //determine the used method and salt
770  $len = strlen($crypt);
771  if(substr($crypt,0,3) == '$1$'){
772    $method = 'smd5';
773    $salt   = substr($crypt,3,8);
774  }elseif(substr($crypt,0,6) == '{SSHA}'){
775    $method = 'ssha';
776    $salt   = substr(base64_decode(substr($crypt, 6)),20);
777  }elseif($len == 32){
778    $method = 'md5';
779  }elseif($len == 40){
780    $method = 'sha1';
781  }elseif($len == 16){
782    $method = 'mysql';
783  }elseif($len == 41 && $crypt[0] == '*'){
784    $method = 'my411';
785  }else{
786    $method = 'crypt';
787    $salt   = substr($crypt,0,2);
788  }
789
790  //crypt and compare
791  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
792    return true;
793  }
794  return false;
795}
796
797//Setup VIM: ex: et ts=2 enc=utf-8 :
798