xref: /dokuwiki/inc/auth.php (revision ce6b63d97068e71369bad95e7959d0110717bbfd)
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  // some ACL level defines
17  define('AUTH_NONE',0);
18  define('AUTH_READ',1);
19  define('AUTH_EDIT',2);
20  define('AUTH_CREATE',4);
21  define('AUTH_UPLOAD',8);
22  define('AUTH_DELETE',16);
23  define('AUTH_ADMIN',255);
24
25  global $conf;
26
27  if($conf['useacl']){
28    require_once(DOKU_INC.'inc/blowfish.php');
29    require_once(DOKU_INC.'inc/mail.php');
30
31    global $auth;
32
33    // load the the backend auth functions and instantiate the auth object
34    if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
35      require_once(DOKU_INC.'inc/auth/basic.class.php');
36      require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
37
38      $auth_class = "auth_".$conf['authtype'];
39      if (class_exists($auth_class)) {
40        $auth = new $auth_class();
41        if ($auth->success == false) {
42          unset($auth);
43          msg($lang['authtempfail'], -1);
44
45          // turn acl config setting off for the rest of this page
46          $conf['useacl'] = 0;
47        }
48      } else {
49        nice_die($lang['authmodfailed']);
50      }
51    } else {
52      nice_die($lang['authmodfailed']);
53    }
54  }
55
56  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5($conf['title']));
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  global $cache_authname;
384  $cache =& $cache_authname;
385
386  if (!isset($cache[$name][$skip_group])) {
387    if($skip_group && $name{0} =='@'){
388      $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
389                                                    "'%'.dechex(ord('\\1'))",substr($name,1));
390    }else{
391      $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
392                                                "'%'.dechex(ord('\\1'))",$name);
393    }
394  }
395
396  return $cache[$name][$skip_group];
397}
398
399/**
400 * Create a pronouncable password
401 *
402 * @author  Andreas Gohr <andi@splitbrain.org>
403 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
404 *
405 * @return string  pronouncable password
406 */
407function auth_pwgen(){
408  $pw = '';
409  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
410  $v  = 'aeiou';              //vowels
411  $a  = $c.$v;                //both
412
413  //use two syllables...
414  for($i=0;$i < 2; $i++){
415    $pw .= $c[rand(0, strlen($c)-1)];
416    $pw .= $v[rand(0, strlen($v)-1)];
417    $pw .= $a[rand(0, strlen($a)-1)];
418  }
419  //... and add a nice number
420  $pw .= rand(10,99);
421
422  return $pw;
423}
424
425/**
426 * Sends a password to the given user
427 *
428 * @author  Andreas Gohr <andi@splitbrain.org>
429 *
430 * @return bool  true on success
431 */
432function auth_sendPassword($user,$password){
433  global $conf;
434  global $lang;
435  global $auth;
436
437  $hdrs  = '';
438  $userinfo = $auth->getUserData($user);
439
440  if(!$userinfo['mail']) return false;
441
442  $text = rawLocale('password');
443  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
444  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
445  $text = str_replace('@LOGIN@',$user,$text);
446  $text = str_replace('@PASSWORD@',$password,$text);
447  $text = str_replace('@TITLE@',$conf['title'],$text);
448
449  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
450                   $lang['regpwmail'],
451                   $text,
452                   $conf['mailfrom']);
453}
454
455/**
456 * Register a new user
457 *
458 * This registers a new user - Data is read directly from $_POST
459 *
460 * @author  Andreas Gohr <andi@splitbrain.org>
461 *
462 * @return bool  true on success, false on any error
463 */
464function register(){
465  global $lang;
466  global $conf;
467  global $auth;
468
469  if(!$_POST['save']) return false;
470  if(!$auth->canDo('addUser')) return false;
471
472  //clean username
473  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
474  $_POST['login'] = cleanID($_POST['login']);
475  //clean fullname and email
476  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['fullname']));
477  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['email']));
478
479  if( empty($_POST['login']) ||
480      empty($_POST['fullname']) ||
481      empty($_POST['email']) ){
482    msg($lang['regmissing'],-1);
483    return false;
484  }
485
486  if ($conf['autopasswd']) {
487    $pass = auth_pwgen();                // automatically generate password
488  } elseif (empty($_POST['pass']) ||
489            empty($_POST['passchk'])) {
490    msg($lang['regmissing'], -1);        // complain about missing passwords
491    return false;
492  } elseif ($_POST['pass'] != $_POST['passchk']) {
493    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
494    return false;
495  } else {
496    $pass = $_POST['pass'];              // accept checked and valid password
497  }
498
499  //check mail
500  if(!mail_isvalid($_POST['email'])){
501    msg($lang['regbadmail'],-1);
502    return false;
503  }
504
505  //okay try to create the user
506  if(!$auth->createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email'])){
507    msg($lang['reguexists'],-1);
508    return false;
509  }
510
511  // create substitutions for use in notification email
512  $substitutions = array(
513    'NEWUSER' => $_POST['login'],
514    'NEWNAME' => $_POST['fullname'],
515    'NEWEMAIL' => $_POST['email'],
516  );
517
518  if (!$conf['autopasswd']) {
519    msg($lang['regsuccess2'],1);
520    notify('', 'register', '', $_POST['login'], false, $substitutions);
521    return true;
522  }
523
524  // autogenerated password? then send him the password
525  if (auth_sendPassword($_POST['login'],$pass)){
526    msg($lang['regsuccess'],1);
527    notify('', 'register', '', $_POST['login'], false, $substitutions);
528    return true;
529  }else{
530    msg($lang['regmailfail'],-1);
531    return false;
532  }
533}
534
535/**
536 * Update user profile
537 *
538 * @author    Christopher Smith <chris@jalakai.co.uk>
539 */
540function updateprofile() {
541  global $conf;
542  global $INFO;
543  global $lang;
544  global $auth;
545
546  if(empty($_POST['save'])) return false;
547
548  // should not be able to get here without Profile being possible...
549  if(!$auth->canDo('Profile')) {
550    msg($lang['profna'],-1);
551    return false;
552  }
553
554  if ($_POST['newpass'] != $_POST['passchk']) {
555    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
556    return false;
557  }
558
559  //clean fullname and email
560  $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['fullname']));
561  $_POST['email']    = trim(preg_replace('/[\x00-\x1f:<>&%]+/','',$_POST['email']));
562
563  if (empty($_POST['fullname']) || empty($_POST['email'])) {
564    msg($lang['profnoempty'],-1);
565    return false;
566  }
567
568  if (!mail_isvalid($_POST['email'])){
569    msg($lang['regbadmail'],-1);
570    return false;
571  }
572
573  if ($_POST['fullname'] != $INFO['userinfo']['name']) $changes['name'] = $_POST['fullname'];
574  if ($_POST['email']    != $INFO['userinfo']['mail']) $changes['mail'] = $_POST['email'];
575  if (!empty($_POST['newpass']))  $changes['pass'] = $_POST['newpass'];
576
577  if (!count($changes)) {
578    msg($lang['profnochange'], -1);
579    return false;
580  }
581
582  if ($conf['profileconfirm']) {
583      if (!auth_verifyPassword($_POST['oldpass'],$INFO['userinfo']['pass'])) {
584      msg($lang['badlogin'],-1);
585      return false;
586    }
587  }
588
589  return $auth->modifyUser($_SERVER['REMOTE_USER'], $changes);
590}
591
592/**
593 * Send a  new password
594 *
595 * This function handles both phases of the password reset:
596 *
597 *   - handling the first request of password reset
598 *   - validating the password reset auth token
599 *
600 * @author Benoit Chesneau <benoit@bchesneau.info>
601 * @author Chris Smith <chris@jalakai.co.uk>
602 * @author Andreas Gohr <andi@splitbrain.org>
603 *
604 * @return bool true on success, false on any error
605*/
606function act_resendpwd(){
607    global $lang;
608    global $conf;
609    global $auth;
610
611    if(!actionOK('resendpwd')) return false;
612
613    // should not be able to get here without modPass being possible...
614    if(!$auth->canDo('modPass')) {
615        msg($lang['resendna'],-1);
616        return false;
617    }
618
619    $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
620
621    if($token){
622        // we're in token phase
623
624        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
625        if(!@file_exists($tfile)){
626            msg($lang['resendpwdbadauth'],-1);
627            return false;
628        }
629        $user = io_readfile($tfile);
630        @unlink($tfile);
631        $userinfo = $auth->getUserData($user);
632        if(!$userinfo['mail']) {
633            msg($lang['resendpwdnouser'], -1);
634            return false;
635        }
636
637        $pass = auth_pwgen();
638        if (!$auth->modifyUser($user,array('pass' => $pass))) {
639            msg('error modifying user data',-1);
640            return false;
641        }
642
643        if (auth_sendPassword($user,$pass)) {
644            msg($lang['resendpwdsuccess'],1);
645        } else {
646            msg($lang['regmailfail'],-1);
647        }
648        return true;
649
650    } else {
651        // we're in request phase
652
653        if(!$_POST['save']) return false;
654
655        if (empty($_POST['login'])) {
656            msg($lang['resendpwdmissing'], -1);
657            return false;
658        } else {
659            $user = $_POST['login'];
660        }
661
662        $userinfo = $auth->getUserData($user);
663        if(!$userinfo['mail']) {
664            msg($lang['resendpwdnouser'], -1);
665            return false;
666        }
667
668        // generate auth token
669        $token = md5(auth_cookiesalt().$user); //secret but user based
670        $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
671        $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
672
673        io_saveFile($tfile,$user);
674
675        $text = rawLocale('pwconfirm');
676        $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
677        $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
678        $text = str_replace('@LOGIN@',$user,$text);
679        $text = str_replace('@TITLE@',$conf['title'],$text);
680        $text = str_replace('@CONFIRM@',$url,$text);
681
682        if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
683                     $lang['regpwmail'],
684                     $text,
685                     $conf['mailfrom'])){
686            msg($lang['resendpwdconfirm'],1);
687        }else{
688            msg($lang['regmailfail'],-1);
689        }
690        return true;
691    }
692
693    return false; // never reached
694}
695
696/**
697 * Uses a regular expresion to check if a given mail address is valid
698 *
699 * May not be completly RFC conform!
700 *
701 * @link    http://www.webmasterworld.com/forum88/135.htm
702 *
703 * @param   string $email the address to check
704 * @return  bool          true if address is valid
705 */
706function isvalidemail($email){
707  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
708}
709
710/**
711 * Encrypts a password using the given method and salt
712 *
713 * If the selected method needs a salt and none was given, a random one
714 * is chosen.
715 *
716 * The following methods are understood:
717 *
718 *   smd5  - Salted MD5 hashing
719 *   md5   - Simple MD5 hashing
720 *   sha1  - SHA1 hashing
721 *   ssha  - Salted SHA1 hashing
722 *   crypt - Unix crypt
723 *   mysql - MySQL password (old method)
724 *   my411 - MySQL 4.1.1 password
725 *
726 * @author  Andreas Gohr <andi@splitbrain.org>
727 * @return  string  The crypted password
728 */
729function auth_cryptPassword($clear,$method='',$salt=''){
730  global $conf;
731  if(empty($method)) $method = $conf['passcrypt'];
732
733  //prepare a salt
734  if(empty($salt)) $salt = md5(uniqid(rand(), true));
735
736  switch(strtolower($method)){
737    case 'smd5':
738        return crypt($clear,'$1$'.substr($salt,0,8).'$');
739    case 'md5':
740      return md5($clear);
741    case 'sha1':
742      return sha1($clear);
743    case 'ssha':
744      $salt=substr($salt,0,4);
745      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
746    case 'crypt':
747      return crypt($clear,substr($salt,0,2));
748    case 'mysql':
749      //from http://www.php.net/mysql comment by <soren at byu dot edu>
750      $nr=0x50305735;
751      $nr2=0x12345671;
752      $add=7;
753      $charArr = preg_split("//", $clear);
754      foreach ($charArr as $char) {
755        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
756        $charVal = ord($char);
757        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
758        $nr2 += ($nr2 << 8) ^ $nr;
759        $add += $charVal;
760      }
761      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
762    case 'my411':
763      return '*'.sha1(pack("H*", sha1($clear)));
764    default:
765      msg("Unsupported crypt method $method",-1);
766  }
767}
768
769/**
770 * Verifies a cleartext password against a crypted hash
771 *
772 * The method and salt used for the crypted hash is determined automatically
773 * then the clear text password is crypted using the same method. If both hashs
774 * match true is is returned else false
775 *
776 * @author  Andreas Gohr <andi@splitbrain.org>
777 * @return  bool
778 */
779function auth_verifyPassword($clear,$crypt){
780  $method='';
781  $salt='';
782
783  //determine the used method and salt
784  $len = strlen($crypt);
785  if(substr($crypt,0,3) == '$1$'){
786    $method = 'smd5';
787    $salt   = substr($crypt,3,8);
788  }elseif(substr($crypt,0,6) == '{SSHA}'){
789    $method = 'ssha';
790    $salt   = substr(base64_decode(substr($crypt, 6)),20);
791  }elseif($len == 32){
792    $method = 'md5';
793  }elseif($len == 40){
794    $method = 'sha1';
795  }elseif($len == 16){
796    $method = 'mysql';
797  }elseif($len == 41 && $crypt[0] == '*'){
798    $method = 'my411';
799  }else{
800    $method = 'crypt';
801    $salt   = substr($crypt,0,2);
802  }
803
804  //crypt and compare
805  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
806    return true;
807  }
808  return false;
809}
810
811//Setup VIM: ex: et ts=2 enc=utf-8 :
812