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