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