xref: /dokuwiki/inc/auth.php (revision 37065e654096bbf1a82d3bd11d990592b4d4b174)
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
182  if(isset($_SESSION[$conf['title']]['auth']['user']))
183    unset($_SESSION[$conf['title']]['auth']['user']);
184  if(isset($_SESSION[$conf['title']]['auth']['pass']))
185    unset($_SESSION[$conf['title']]['auth']['pass']);
186  if(isset($_SESSION[$conf['title']]['auth']['info']))
187    unset($_SESSION[$conf['title']]['auth']['info']);
188  if(isset($_SERVER['REMOTE_USER']))
189    unset($_SERVER['REMOTE_USER']);
190  $USERINFO=null; //FIXME
191  setcookie(DOKU_COOKIE,'',time()-600000,'/');
192}
193
194/**
195 * Convinience function for auth_aclcheck()
196 *
197 * This checks the permissions for the current user
198 *
199 * @author  Andreas Gohr <andi@splitbrain.org>
200 *
201 * @param  string  $id  page ID
202 * @return int          permission level
203 */
204function auth_quickaclcheck($id){
205  global $conf;
206  global $USERINFO;
207  # if no ACL is used always return upload rights
208  if(!$conf['useacl']) return AUTH_UPLOAD;
209  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
210}
211
212/**
213 * Returns the maximum rights a user has for
214 * the given ID or its namespace
215 *
216 * @author  Andreas Gohr <andi@splitbrain.org>
217 *
218 * @param  string  $id     page ID
219 * @param  string  $user   Username
220 * @param  array   $groups Array of groups the user is in
221 * @return int             permission level
222 */
223function auth_aclcheck($id,$user,$groups){
224  global $conf;
225  global $AUTH_ACL;
226
227  # if no ACL is used always return upload rights
228  if(!$conf['useacl']) return AUTH_UPLOAD;
229
230  //if user is superuser return 255 (acl_admin)
231  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
232
233  //make sure groups is an array
234  if(!is_array($groups)) $groups = array();
235
236  //prepend groups with @
237  $cnt = count($groups);
238  for($i=0; $i<$cnt; $i++){
239    $groups[$i] = '@'.$groups[$i];
240  }
241  //if user is in superuser group return 255 (acl_admin)
242  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
243
244  $ns    = getNS($id);
245  $perm  = -1;
246
247  if($user){
248    //add ALL group
249    $groups[] = '@ALL';
250    //add User
251    $groups[] = $user;
252    //build regexp
253    $regexp   = join('|',$groups);
254  }else{
255    $regexp = '@ALL';
256  }
257
258  //check exact match first
259  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
260  if(count($matches)){
261    foreach($matches as $match){
262      $match = preg_replace('/#.*$/','',$match); //ignore comments
263      $acl   = preg_split('/\s+/',$match);
264      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
265      if($acl[2] > $perm){
266        $perm = $acl[2];
267      }
268    }
269    if($perm > -1){
270      //we had a match - return it
271      return $perm;
272    }
273  }
274
275  //still here? do the namespace checks
276  if($ns){
277    $path = $ns.':\*';
278  }else{
279    $path = '\*'; //root document
280  }
281
282  do{
283    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
284    if(count($matches)){
285      foreach($matches as $match){
286        $match = preg_replace('/#.*$/','',$match); //ignore comments
287        $acl   = preg_split('/\s+/',$match);
288        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
289        if($acl[2] > $perm){
290          $perm = $acl[2];
291        }
292      }
293      //we had a match - return it
294      return $perm;
295    }
296
297    //get next higher namespace
298    $ns   = getNS($ns);
299
300    if($path != '\*'){
301      $path = $ns.':\*';
302      if($path == ':\*') $path = '\*';
303    }else{
304      //we did this already
305      //looks like there is something wrong with the ACL
306      //break here
307      return $perm;
308    }
309  }while(1); //this should never loop endless
310
311  //still here? return no permissions
312  return AUTH_NONE;
313}
314
315/**
316 * Create a pronouncable password
317 *
318 * @author  Andreas Gohr <andi@splitbrain.org>
319 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
320 *
321 * @return string  pronouncable password
322 */
323function auth_pwgen(){
324  $pw = '';
325  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
326  $v  = 'aeiou';              //vowels
327  $a  = $c.$v;                //both
328
329  //use two syllables...
330  for($i=0;$i < 2; $i++){
331    $pw .= $c[rand(0, strlen($c)-1)];
332    $pw .= $v[rand(0, strlen($v)-1)];
333    $pw .= $a[rand(0, strlen($a)-1)];
334  }
335  //... and add a nice number
336  $pw .= rand(10,99);
337
338  return $pw;
339}
340
341/**
342 * Sends a password to the given user
343 *
344 * @author  Andreas Gohr <andi@splitbrain.org>
345 *
346 * @return bool  true on success
347 */
348function auth_sendPassword($user,$password){
349  global $conf;
350  global $lang;
351  $hdrs  = '';
352  $userinfo = auth_getUserData($user);
353
354  if(!$userinfo['mail']) return false;
355
356  $text = rawLocale('password');
357  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
358  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
359  $text = str_replace('@LOGIN@',$user,$text);
360  $text = str_replace('@PASSWORD@',$password,$text);
361  $text = str_replace('@TITLE@',$conf['title'],$text);
362
363  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
364                   $lang['regpwmail'],
365                   $text,
366                   $conf['mailfrom']);
367}
368
369/**
370 * Register a new user
371 *
372 * This registers a new user - Data is read directly from $_POST
373 *
374 * @author  Andreas Gohr <andi@splitbrain.org>
375 *
376 * @return bool  true on success, false on any error
377 */
378function register(){
379  global $lang;
380  global $conf;
381
382  if(!$_POST['save']) return false;
383
384  //clean username
385  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
386  $_POST['login'] = cleanID($_POST['login']);
387  //clean fullname and email
388  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
389  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
390
391  if( empty($_POST['login']) ||
392      empty($_POST['fullname']) ||
393      empty($_POST['email']) ){
394    msg($lang['regmissing'],-1);
395    return false;
396  }
397
398  if ($conf['autopasswd']) {
399    $pass = auth_pwgen();                // automatically generate password
400  } elseif (empty($_POST['pass']) ||
401            empty($_POST['passchk'])) {
402    msg($lang['regmissing'], -1);        // complain about missing passwords
403    return false;
404  } elseif ($_POST['pass'] != $_POST['passchk']) {
405    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
406    return false;
407  } else {
408    $pass = $_POST['pass'];              // accept checked and valid password
409  }
410
411  //check mail
412  if(!mail_isvalid($_POST['email'])){
413    msg($lang['regbadmail'],-1);
414    return false;
415  }
416
417  //okay try to create the user
418  $pass = auth_createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email']);
419  if(empty($pass)){
420    msg($lang['reguexists'],-1);
421    return false;
422  }
423
424  if (!$conf['autopasswd']) {
425    msg($lang['regsuccess2'],1);
426    return true;
427  }
428
429  // autogenerated password? then send him the password
430  if (auth_sendPassword($_POST['login'],$pass)){
431    msg($lang['regsuccess'],1);
432    return true;
433  }else{
434    msg($lang['regmailfail'],-1);
435    return false;
436  }
437}
438
439/**
440 * Uses a regular expresion to check if a given mail address is valid
441 *
442 * May not be completly RFC conform!
443 *
444 * @link    http://www.webmasterworld.com/forum88/135.htm
445 *
446 * @param   string $email the address to check
447 * @return  bool          true if address is valid
448 */
449function isvalidemail($email){
450  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
451}
452
453/**
454 * Encrypts a password using the given method and salt
455 *
456 * If the selected method needs a salt and none was given, a random one
457 * is chosen.
458 *
459 * The following methods are understood:
460 *
461 *   smd5  - Salted MD5 hashing
462 *   md5   - Simple MD5 hashing
463 *   sha1  - SHA1 hashing
464 *   ssha  - Salted SHA1 hashing
465 *   crypt - Unix crypt
466 *   mysql - MySQL password (old method)
467 *   my411 - MySQL 4.1.1 password
468 *
469 * @author  Andreas Gohr <andi@splitbrain.org>
470 * @return  string  The crypted password
471 */
472function auth_cryptPassword($clear,$method='',$salt=''){
473  global $conf;
474  if(empty($method)) $method = $conf['passcrypt'];
475
476  //prepare a salt
477  if(empty($salt)) $salt = md5(uniqid(rand(), true));
478
479  switch(strtolower($method)){
480    case 'smd5':
481        return crypt($clear,'$1$'.substr($salt,0,8).'$');
482    case 'md5':
483      return md5($clear);
484    case 'sha1':
485      return sha1($clear);
486    case 'ssha':
487      $salt=substr($salt,0,4);
488      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
489    case 'crypt':
490      return crypt($clear,substr($salt,0,2));
491    case 'mysql':
492      //from http://www.php.net/mysql comment by <soren at byu dot edu>
493      $nr=0x50305735;
494      $nr2=0x12345671;
495      $add=7;
496      $charArr = preg_split("//", $clear);
497      foreach ($charArr as $char) {
498        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
499        $charVal = ord($char);
500        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
501        $nr2 += ($nr2 << 8) ^ $nr;
502        $add += $charVal;
503      }
504      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
505    case 'my411':
506      return '*'.sha1(pack("H*", sha1($clear)));
507    default:
508      msg("Unsupported crypt method $method",-1);
509  }
510}
511
512/**
513 * Verifies a cleartext password against a crypted hash
514 *
515 * The method and salt used for the crypted hash is determined automatically
516 * then the clear text password is crypted using the same method. If both hashs
517 * match true is is returned else false
518 *
519 * @author  Andreas Gohr <andi@splitbrain.org>
520 * @return  bool
521 */
522function auth_verifyPassword($clear,$crypt){
523  $method='';
524  $salt='';
525
526  //determine the used method and salt
527  $len = strlen($crypt);
528  if(substr($crypt,0,3) == '$1$'){
529    $method = 'smd5';
530    $salt   = substr($crypt,3,8);
531  }elseif(substr($crypt,0,6) == '{SSHA}'){
532    $method = 'ssha';
533    $salt   = substr(base64_decode(substr($crypt, 6)),20);
534  }elseif($len == 32){
535    $method = 'md5';
536  }elseif($len == 40){
537    $method = 'sha1';
538  }elseif($len == 16){
539    $method = 'mysql';
540  }elseif($len == 41 && $crypt[0] == '*'){
541    $method = 'my411';
542  }else{
543    $method = 'crypt';
544    $salt   = substr($crypt,0,2);
545  }
546
547  //crypt and compare
548  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
549    return true;
550  }
551  return false;
552}
553
554//Setup VIM: ex: et ts=2 enc=utf-8 :
555