xref: /dokuwiki/inc/auth.php (revision e60c9d46bd2b3cbed0ac8754712e54a3d23bf363)
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  require_once(DOKU_INC.'inc/blowfish.php');
16  require_once(DOKU_INC.'inc/mail.php');
17  // load the the auth functions
18  require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.php');
19
20  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5($conf['title']));
21
22  // some ACL level defines
23  define('AUTH_NONE',0);
24  define('AUTH_READ',1);
25  define('AUTH_EDIT',2);
26  define('AUTH_CREATE',4);
27  define('AUTH_UPLOAD',8);
28  define('AUTH_DELETE',16);
29  define('AUTH_ADMIN',255);
30
31  if($conf['useacl']){
32    auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
33    //load ACL into a global array
34    if(is_readable(DOKU_INC.'conf/acl.auth.php')){
35      $AUTH_ACL = file(DOKU_INC.'conf/acl.auth.php');
36    }else{
37      $AUTH_ACL = array();
38    }
39  }
40
41/**
42 * This tries to login the user based on the sent auth credentials
43 *
44 * The authentication works like this: if a username was given
45 * a new login is assumed and user/password are checked. If they
46 * are correct the password is encrypted with blowfish and stored
47 * together with the username in a cookie - the same info is stored
48 * in the session, too. Additonally a browserID is stored in the
49 * session.
50 *
51 * If no username was given the cookie is checked: if the username,
52 * crypted password and browserID match between session and cookie
53 * no further testing is done and the user is accepted
54 *
55 * If a cookie was found but no session info was availabe the
56 * blowfish encrypted password from the cookie is decrypted and
57 * together with username rechecked by calling this function again.
58 *
59 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
60 * are set.
61 *
62 * @author  Andreas Gohr <andi@splitbrain.org>
63 *
64 * @param   string  $user    Username
65 * @param   string  $pass    Cleartext Password
66 * @param   bool    $sticky  Cookie should not expire
67 * @return  bool             true on successful auth
68*/
69function auth_login($user,$pass,$sticky=false){
70  global $USERINFO;
71  global $conf;
72  global $lang;
73  $sticky ? $sticky = true : $sticky = false; //sanity check
74
75  if(isset($user)){
76    //usual login
77    if (auth_checkPass($user,$pass)){
78      // make logininfo globally available
79      $_SERVER['REMOTE_USER'] = $user;
80      $USERINFO = auth_getUserData($user); //FIXME move all references to session
81
82      // set cookie
83      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
84      $cookie = base64_encode("$user|$sticky|$pass");
85      if($sticky) $time = time()+60*60*24*365; //one year
86      setcookie(DOKU_COOKIE,$cookie,$time,'/');
87
88      // set session
89      $_SESSION[$conf['title']]['auth']['user'] = $user;
90      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
91      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
92      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
93      return true;
94    }else{
95      //invalid credentials - log off
96      msg($lang['badlogin'],-1);
97      auth_logoff();
98      return false;
99    }
100  }else{
101    // read cookie information
102    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
103    list($user,$sticky,$pass) = split('\|',$cookie,3);
104    // get session info
105    $session = $_SESSION[$conf['title']]['auth'];
106
107    if($user && $pass){
108      // we got a cookie - see if we can trust it
109      if(isset($session) &&
110        ($session['user'] == $user) &&
111        ($session['pass'] == $pass) &&  //still crypted
112        ($session['buid'] == auth_browseruid()) ){
113        // he has session, cookie and browser right - let him in
114        $_SERVER['REMOTE_USER'] = $user;
115        $USERINFO = $session['info']; //FIXME move all references to session
116        return true;
117      }
118      // no we don't trust it yet - recheck pass
119      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
120      return auth_login($user,$pass,$sticky);
121    }
122  }
123  //just to be sure
124  auth_logoff();
125  return false;
126}
127
128/**
129 * Builds a pseudo UID from browser and IP data
130 *
131 * This is neither unique nor unfakable - still it adds some
132 * security. Using the first part of the IP makes sure
133 * proxy farms like AOLs are stil okay.
134 *
135 * @author  Andreas Gohr <andi@splitbrain.org>
136 *
137 * @return  string  a MD5 sum of various browser headers
138 */
139function auth_browseruid(){
140  $uid  = '';
141  $uid .= $_SERVER['HTTP_USER_AGENT'];
142  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
143  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
144  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
145  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
146  return md5($uid);
147}
148
149/**
150 * Creates a random key to encrypt the password in cookies
151 *
152 * This function tries to read the password for encrypting
153 * cookies from $conf['metadir'].'/_htcookiesalt'
154 * if no such file is found a random key is created and
155 * and stored in this file.
156 *
157 * @author  Andreas Gohr <andi@splitbrain.org>
158 *
159 * @return  string
160 */
161function auth_cookiesalt(){
162  global $conf;
163  $file = $conf['metadir'].'/_htcookiesalt';
164  $salt = io_readFile($file);
165  if(empty($salt)){
166    $salt = uniqid(rand(),true);
167    io_saveFile($file,$salt);
168  }
169  return $salt;
170}
171
172/**
173 * This clears all authenticationdata and thus log the user
174 * off
175 *
176 * @author  Andreas Gohr <andi@splitbrain.org>
177 */
178function auth_logoff(){
179  global $conf;
180  global $USERINFO;
181  unset($_SESSION[$conf['title']]['auth']['user']);
182  unset($_SESSION[$conf['title']]['auth']['pass']);
183  unset($_SESSION[$conf['title']]['auth']['info']);
184  unset($_SERVER['REMOTE_USER']);
185  $USERINFO=null; //FIXME
186  setcookie(DOKU_COOKIE,'',time()-600000,'/');
187}
188
189/**
190 * Convinience function for auth_aclcheck()
191 *
192 * This checks the permissions for the current user
193 *
194 * @author  Andreas Gohr <andi@splitbrain.org>
195 *
196 * @param  string  $id  page ID
197 * @return int          permission level
198 */
199function auth_quickaclcheck($id){
200  global $conf;
201  global $USERINFO;
202  # if no ACL is used always return upload rights
203  if(!$conf['useacl']) return AUTH_UPLOAD;
204  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
205}
206
207/**
208 * Returns the maximum rights a user has for
209 * the given ID or its namespace
210 *
211 * @author  Andreas Gohr <andi@splitbrain.org>
212 *
213 * @param  string  $id     page ID
214 * @param  string  $user   Username
215 * @param  array   $groups Array of groups the user is in
216 * @return int             permission level
217 */
218function auth_aclcheck($id,$user,$groups){
219  global $conf;
220  global $AUTH_ACL;
221
222  # if no ACL is used always return upload rights
223  if(!$conf['useacl']) return AUTH_UPLOAD;
224
225  //if user is superuser return 255 (acl_admin)
226  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
227
228  //make sure groups is an array
229  if(!is_array($groups)) $groups = array();
230
231  //prepend groups with @
232  $cnt = count($groups);
233  for($i=0; $i<$cnt; $i++){
234    $groups[$i] = '@'.$groups[$i];
235  }
236  //if user is in superuser group return 255 (acl_admin)
237  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
238
239  $ns    = getNS($id);
240  $perm  = -1;
241
242  if($user){
243    //add ALL group
244    $groups[] = '@ALL';
245    //add User
246    $groups[] = $user;
247    //build regexp
248    $regexp   = join('|',$groups);
249  }else{
250    $regexp = '@ALL';
251  }
252
253  //check exact match first
254  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
255  if(count($matches)){
256    foreach($matches as $match){
257      $match = preg_replace('/#.*$/','',$match); //ignore comments
258      $acl   = preg_split('/\s+/',$match);
259      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
260      if($acl[2] > $perm){
261        $perm = $acl[2];
262      }
263    }
264    if($perm > -1){
265      //we had a match - return it
266      return $perm;
267    }
268  }
269
270  //still here? do the namespace checks
271  if($ns){
272    $path = $ns.':\*';
273  }else{
274    $path = '\*'; //root document
275  }
276
277  do{
278    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
279    if(count($matches)){
280      foreach($matches as $match){
281        $match = preg_replace('/#.*$/','',$match); //ignore comments
282        $acl   = preg_split('/\s+/',$match);
283        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
284        if($acl[2] > $perm){
285          $perm = $acl[2];
286        }
287      }
288      //we had a match - return it
289      return $perm;
290    }
291
292    //get next higher namespace
293    $ns   = getNS($ns);
294
295    if($path != '\*'){
296      $path = $ns.':\*';
297      if($path == ':\*') $path = '\*';
298    }else{
299      //we did this already
300      //looks like there is something wrong with the ACL
301      //break here
302      return $perm;
303    }
304  }while(1); //this should never loop endless
305
306  //still here? return no permissions
307  return AUTH_NONE;
308}
309
310/**
311 * Create a pronouncable password
312 *
313 * @author  Andreas Gohr <andi@splitbrain.org>
314 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
315 *
316 * @return string  pronouncable password
317 */
318function auth_pwgen(){
319  $pw = '';
320  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
321  $v  = 'aeiou';              //vowels
322  $a  = $c.$v;                //both
323
324  //use two syllables...
325  for($i=0;$i < 2; $i++){
326    $pw .= $c[rand(0, strlen($c)-1)];
327    $pw .= $v[rand(0, strlen($v)-1)];
328    $pw .= $a[rand(0, strlen($a)-1)];
329  }
330  //... and add a nice number
331  $pw .= rand(10,99);
332
333  return $pw;
334}
335
336/**
337 * Sends a password to the given user
338 *
339 * @author  Andreas Gohr <andi@splitbrain.org>
340 *
341 * @return bool  true on success
342 */
343function auth_sendPassword($user,$password){
344  global $conf;
345  global $lang;
346  $hdrs  = '';
347  $userinfo = auth_getUserData($user);
348
349  if(!$userinfo['mail']) return false;
350
351  $text = rawLocale('password');
352  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
353  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
354  $text = str_replace('@LOGIN@',$user,$text);
355  $text = str_replace('@PASSWORD@',$password,$text);
356  $text = str_replace('@TITLE@',$conf['title'],$text);
357
358  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
359                   $lang['regpwmail'],
360                   $text,
361                   $conf['mailfrom']);
362}
363
364/**
365 * Register a new user
366 *
367 * This registers a new user - Data is read directly from $_POST
368 *
369 * @author  Andreas Gohr <andi@splitbrain.org>
370 *
371 * @return bool  true on success, false on any error
372 */
373function register(){
374  global $lang;
375  global $conf;
376
377  if(!$_POST['save']) return false;
378
379  //clean username
380  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
381  $_POST['login'] = cleanID($_POST['login']);
382  //clean fullname and email
383  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
384  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
385
386  if( empty($_POST['login']) ||
387      empty($_POST['fullname']) ||
388      empty($_POST['email']) ){
389    msg($lang['regmissing'],-1);
390    return false;
391  }
392
393  if ($conf['autopasswd']) {
394    $pass = auth_pwgen();                // automatically generate password
395  } elseif (empty($_POST['pass']) ||
396            empty($_POST['passchk'])) {
397    msg($lang['regmissing'], -1);        // complain about missing passwords
398    return false;
399  } elseif ($_POST['pass'] != $_POST['passchk']) {
400    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
401    return false;
402  } else {
403    $pass = $_POST['pass'];              // accept checked and valid password
404  }
405
406  //check mail
407  if(!mail_isvalid($_POST['email'])){
408    msg($lang['regbadmail'],-1);
409    return false;
410  }
411
412  //okay try to create the user
413  $pass = auth_createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email']);
414  if(empty($pass)){
415    msg($lang['reguexists'],-1);
416    return false;
417  }
418
419  if (!$conf['autopasswd']) {
420    msg($lang['regsuccess2'],1);
421    return true;
422  }
423
424  // autogenerated password? then send him the password
425  if (auth_sendPassword($_POST['login'],$pass)){
426    msg($lang['regsuccess'],1);
427    return true;
428  }else{
429    msg($lang['regmailfail'],-1);
430    return false;
431  }
432}
433
434/**
435 * Uses a regular expresion to check if a given mail address is valid
436 *
437 * May not be completly RFC conform!
438 *
439 * @link    http://www.webmasterworld.com/forum88/135.htm
440 *
441 * @param   string $email the address to check
442 * @return  bool          true if address is valid
443 */
444function isvalidemail($email){
445  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
446}
447
448/**
449 * Encrypts a password using the given method and salt
450 *
451 * If the selected method needs a salt and none was given, a random one
452 * is chosen.
453 *
454 * The following methods are understood:
455 *
456 *   smd5  - Salted MD5 hashing
457 *   md5   - Simple MD5 hashing
458 *   sha1  - SHA1 hashing
459 *   ssha  - Salted SHA1 hashing
460 *   crypt - Unix crypt
461 *   mysql - MySQL password (old method)
462 *   my411 - MySQL 4.1.1 password
463 *
464 * @author  Andreas Gohr <andi@splitbrain.org>
465 * @return  string  The crypted password
466 */
467function auth_cryptPassword($clear,$method='',$salt=''){
468  global $conf;
469  if(empty($method)) $method = $conf['passcrypt'];
470
471  //prepare a salt
472  if(empty($salt)) $salt = md5(uniqid(rand(), true));
473
474  switch(strtolower($method)){
475    case 'smd5':
476        return crypt($clear,'$1$'.substr($salt,0,8).'$');
477    case 'md5':
478      return md5($clear);
479    case 'sha1':
480      return sha1($clear);
481    case 'ssha':
482      $salt=substr($salt,0,4);
483      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
484    case 'crypt':
485      return crypt($clear,substr($salt,0,2));
486    case 'mysql':
487      //from http://www.php.net/mysql comment by <soren at byu dot edu>
488      $nr=0x50305735;
489      $nr2=0x12345671;
490      $add=7;
491      $charArr = preg_split("//", $clear);
492      foreach ($charArr as $char) {
493        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
494        $charVal = ord($char);
495        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
496        $nr2 += ($nr2 << 8) ^ $nr;
497        $add += $charVal;
498      }
499      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
500    case 'my411':
501      return '*'.sha1(pack("H*", sha1($clear)));
502    default:
503      msg("Unsupported crypt method $method",-1);
504  }
505}
506
507/**
508 * Verifies a cleartext password against a crypted hash
509 *
510 * The method and salt used for the crypted hash is determined automatically
511 * then the clear text password is crypted using the same method. If both hashs
512 * match true is is returned else false
513 *
514 * @author  Andreas Gohr <andi@splitbrain.org>
515 * @return  bool
516 */
517function auth_verifyPassword($clear,$crypt){
518  $method='';
519  $salt='';
520
521  //determine the used method and salt
522  $len = strlen($crypt);
523  if(substr($crypt,0,3) == '$1$'){
524    $method = 'smd5';
525    $salt   = substr($crypt,3,8);
526  }elseif(substr($crypt,0,6) == '{SSHA}'){
527    $method = 'ssha';
528    $salt   = substr(base64_decode(substr($crypt, 6)),20);
529  }elseif($len == 32){
530    $method = 'md5';
531  }elseif($len == 40){
532    $method = 'sha1';
533  }elseif($len == 16){
534    $method = 'mysql';
535  }elseif($len == 41 && $crypt[0] == '*'){
536    $method = 'my411';
537  }else{
538    $method = 'crypt';
539    $salt   = substr($crypt,0,2);
540  }
541
542  //crypt and compare
543  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
544    return true;
545  }
546  return false;
547}
548
549//Setup VIM: ex: et ts=2 enc=utf-8 :
550