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