xref: /dokuwiki/inc/auth.php (revision ae3f21345cde027cf921d0f219f3db91969461ab)
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');
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()-3600);
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  for($i=0; $i<count($groups); $i++){
226    $groups[$i] = '@'.$groups[$i];
227  }
228  //if user is in superuser group return 255 (acl_admin)
229  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
230
231  $ns    = getNS($id);
232  $perm  = -1;
233
234  if($user){
235    //add ALL group
236    $groups[] = '@ALL';
237    //add User
238    $groups[] = $user;
239    //build regexp
240    $regexp   = join('|',$groups);
241  }else{
242    $regexp = '@ALL';
243  }
244
245  //check exact match first
246  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
247  if(count($matches)){
248    foreach($matches as $match){
249      $match = preg_replace('/#.*$/','',$match); //ignore comments
250      $acl   = preg_split('/\s+/',$match);
251      if($acl[2] > AUTH_UPLOAD) $acl[2] = AUTH_UPLOAD; //no admins in the ACL!
252      if($acl[2] > $perm){
253        $perm = $acl[2];
254      }
255    }
256    if($perm > -1){
257      //we had a match - return it
258      return $perm;
259    }
260  }
261
262  //still here? do the namespace checks
263  if($ns){
264    $path = $ns.':\*';
265  }else{
266    $path = '\*'; //root document
267  }
268
269  do{
270    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
271    if(count($matches)){
272      foreach($matches as $match){
273        $match = preg_replace('/#.*$/','',$match); //ignore comments
274        $acl   = preg_split('/\s+/',$match);
275        if($acl[2] > AUTH_UPLOAD) $acl[2] = AUTH_UPLOAD; //no admins in the ACL!
276        if($acl[2] > $perm){
277          $perm = $acl[2];
278        }
279      }
280      //we had a match - return it
281      return $perm;
282    }
283
284    //get next higher namespace
285    $ns   = getNS($ns);
286
287    if($path != '\*'){
288      $path = $ns.':\*';
289      if($path == ':\*') $path = '\*';
290    }else{
291      //we did this already
292      //looks like there is something wrong with the ACL
293      //break here
294      return $perm;
295    }
296  }while(1); //this should never loop endless
297}
298
299/**
300 * Create a pronouncable password
301 *
302 * @author  Andreas Gohr <andi@splitbrain.org>
303 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
304 *
305 * @return string  pronouncable password
306 */
307function auth_pwgen(){
308  $pw = '';
309  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
310  $v  = 'aeiou';              //vowels
311  $a  = $c.$v;                //both
312
313  //use two syllables...
314  for($i=0;$i < 2; $i++){
315    $pw .= $c[rand(0, strlen($c)-1)];
316    $pw .= $v[rand(0, strlen($v)-1)];
317    $pw .= $a[rand(0, strlen($a)-1)];
318  }
319  //... and add a nice number
320  $pw .= rand(10,99);
321
322  return $pw;
323}
324
325/**
326 * Sends a password to the given user
327 *
328 * @author  Andreas Gohr <andi@splitbrain.org>
329 *
330 * @return bool  true on success
331 */
332function auth_sendPassword($user,$password){
333  global $conf;
334  global $lang;
335  $hdrs  = '';
336  $userinfo = auth_getUserData($user);
337
338  if(!$userinfo['mail']) return false;
339
340  $text = rawLocale('password');
341  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
342  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
343  $text = str_replace('@LOGIN@',$user,$text);
344  $text = str_replace('@PASSWORD@',$password,$text);
345  $text = str_replace('@TITLE@',$conf['title'],$text);
346
347  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
348                   $lang['regpwmail'],
349                   $text,
350                   $conf['mailfrom']);
351}
352
353/**
354 * Register a new user
355 *
356 * This registers a new user - Data is read directly from $_POST
357 *
358 * @author  Andreas Gohr <andi@splitbrain.org>
359 *
360 * @return bool  true on success, false on any error
361 */
362function register(){
363  global $lang;
364  global $conf;
365
366  if(!$_POST['save']) return false;
367  if(!$conf['openregister']) return false;
368
369  //clean username
370  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
371  $_POST['login'] = cleanID($_POST['login']);
372  //clean fullname and email
373  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
374  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
375
376  if( empty($_POST['login']) ||
377      empty($_POST['fullname']) ||
378      empty($_POST['email']) ){
379    msg($lang['regmissing'],-1);
380    return false;
381  }
382
383  //check mail
384  if(!mail_isvalid($_POST['email'])){
385    msg($lang['regbadmail'],-1);
386    return false;
387  }
388
389  //okay try to create the user
390  $pass = auth_createUser($_POST['login'],$_POST['fullname'],$_POST['email']);
391  if(empty($pass)){
392    msg($lang['reguexists'],-1);
393    return false;
394  }
395
396  //send him the password
397  if (auth_sendPassword($_POST['login'],$pass)){
398    msg($lang['regsuccess'],1);
399    return true;
400  }else{
401    msg($lang['regmailfail'],-1);
402    return false;
403  }
404}
405
406/**
407 * Uses a regular expresion to check if a given mail address is valid
408 *
409 * May not be completly RFC conform!
410 *
411 * @link    http://www.webmasterworld.com/forum88/135.htm
412 *
413 * @param   string $email the address to check
414 * @return  bool          true if address is valid
415 */
416function isvalidemail($email){
417  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
418}
419
420
421?>
422