xref: /dokuwiki/inc/auth.php (revision ed7b5f0908941f1bacef7e7c3a02c106a42cd5cc)
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_GRANT',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 * blowish 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 browserdata
123 *
124 * This is neither unique nor unfakable - still it adds some
125 * security
126 *
127 * @author  Andreas Gohr <andi@splitbrain.org>
128 *
129 * @return  string  a MD5 sum of various browser headers
130 */
131function auth_browseruid(){
132  $uid  = '';
133  $uid .= $_SERVER['HTTP_USER_AGENT'];
134  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
135  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
136  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
137  return md5($uid);
138}
139
140/**
141 * Creates a random key to encrypt the password in cookies
142 *
143 * This function tries to read the password for encrypting
144 * cookies from $conf['datadir'].'/.cache/.htcookiesalt'
145 * if no such file is found a random key is created and
146 * and stored in this file.
147 *
148 * @author  Andreas Gohr <andi@splitbrain.org>
149 *
150 * @return  string
151 */
152function auth_cookiesalt(){
153  global $conf;
154  $file = $conf['datadir'].'/.cache/.htcookiesalt';
155  $salt = io_readFile($file);
156  if(empty($salt)){
157    $salt = uniqid(rand(),true);
158    io_saveFile($file,$salt);
159  }
160  return $salt;
161}
162
163/**
164 * This clears all authenticationdata and thus log the user
165 * off
166 *
167 * @author  Andreas Gohr <andi@splitbrain.org>
168 */
169function auth_logoff(){
170  global $conf;
171  global $USERINFO;
172  unset($_SESSION[$conf['title']]['auth']['user']);
173  unset($_SESSION[$conf['title']]['auth']['pass']);
174  unset($_SESSION[$conf['title']]['auth']['info']);
175  unset($_SERVER['REMOTE_USER']);
176  $USERINFO=null; //FIXME
177  setcookie('DokuWikiAUTH','',time()-3600);
178}
179
180/**
181 * Convinience function for auth_aclcheck()
182 *
183 * This checks the permissions for the current user
184 *
185 * @author  Andreas Gohr <andi@splitbrain.org>
186 *
187 * @param  string  $id  page ID
188 * @return int          permission level
189 */
190function auth_quickaclcheck($id){
191  global $conf;
192  global $USERINFO;
193  # if no ACL is used always return upload rights
194  if(!$conf['useacl']) return AUTH_UPLOAD;
195  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
196}
197
198/**
199 * Returns the maximum rights a user has for
200 * the given ID or its namespace
201 *
202 * @author  Andreas Gohr <andi@splitbrain.org>
203 *
204 * @param  string  $id     page ID
205 * @param  string  $user   Username
206 * @param  array   $groups Array of groups the user is in
207 * @return int             permission level
208 */
209function auth_aclcheck($id,$user,$groups){
210  global $conf;
211  global $AUTH_ACL;
212
213  # if no ACL is used always return upload rights
214  if(!$conf['useacl']) return AUTH_UPLOAD;
215
216  $ns    = getNS($id);
217  $perm  = -1;
218
219  if($user){
220    //prepend groups with @
221    for($i=0; $i<count($groups); $i++){
222      $groups[$i] = '@'.$groups[$i];
223    }
224    //add ALL group
225    $groups[] = '@ALL';
226    //add User
227    $groups[] = $user;
228    //build regexp
229    $regexp   = join('|',$groups);
230  }else{
231    $regexp = '@ALL';
232  }
233
234  //check exact match first
235  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
236  if(count($matches)){
237    foreach($matches as $match){
238      $match = preg_replace('/#.*$/','',$match); //ignore comments
239      $acl   = preg_split('/\s+/',$match);
240      if($acl[2] > $perm){
241        $perm = $acl[2];
242      }
243    }
244    if($perm > -1){
245      //we had a match - return it
246      return $perm;
247    }
248  }
249
250  //still here? do the namespace checks
251  if($ns){
252    $path = $ns.':\*';
253  }else{
254    $path = '\*'; //root document
255  }
256
257  do{
258    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
259    if(count($matches)){
260      foreach($matches as $match){
261        $match = preg_replace('/#.*$/','',$match); //ignore comments
262        $acl   = preg_split('/\s+/',$match);
263        if($acl[2] > $perm){
264          $perm = $acl[2];
265        }
266      }
267      //we had a match - return it
268      return $perm;
269    }
270
271    //get next higher namespace
272    $ns   = getNS($ns);
273
274    if($path != '\*'){
275      $path = $ns.':\*';
276      if($path == ':\*') $path = '\*';
277    }else{
278      //we did this already
279      //looks like there is something wrong with the ACL
280      //break here
281      return $perm;
282    }
283  }while(1); //this should never loop endless
284}
285
286/**
287 * Create a pronouncable password
288 *
289 * @author  Andreas Gohr <andi@splitbrain.org>
290 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
291 *
292 * @return string  pronouncable password
293 */
294function auth_pwgen(){
295  $pw = '';
296  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
297  $v  = 'aeiou';              //vowels
298  $a  = $c.$v;                //both
299
300  //use two syllables...
301  for($i=0;$i < 2; $i++){
302    $pw .= $c[rand(0, strlen($c)-1)];
303    $pw .= $v[rand(0, strlen($v)-1)];
304    $pw .= $a[rand(0, strlen($a)-1)];
305  }
306  //... and add a nice number
307  $pw .= rand(10,99);
308
309  return $pw;
310}
311
312/**
313 * Sends a password to the given user
314 *
315 * @author  Andreas Gohr <andi@splitbrain.org>
316 *
317 * @return bool  true on success
318 */
319function auth_sendPassword($user,$password){
320  global $conf;
321  global $lang;
322  $hdrs  = '';
323  $userinfo = auth_getUserData($user);
324
325  if(!$userinfo['mail']) return false;
326
327  $text = rawLocale('password');
328  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
329  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
330  $text = str_replace('@LOGIN@',$user,$text);
331  $text = str_replace('@PASSWORD@',$password,$text);
332  $text = str_replace('@TITLE@',$conf['title'],$text);
333
334  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
335                   $lang['regpwmail'],
336                   $text,
337                   $conf['mailfrom']);
338}
339
340/**
341 * Register a new user
342 *
343 * This registers a new user - Data is read directly from $_POST
344 *
345 * @author  Andreas Gohr <andi@splitbrain.org>
346 *
347 * @return bool  true on success, false on any error
348 */
349function register(){
350  global $lang;
351  global $conf;
352
353  if(!$_POST['save']) return false;
354  if(!$conf['openregister']) return false;
355
356  //clean username
357  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
358  $_POST['login'] = cleanID($_POST['login']);
359  //clean fullname and email
360  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
361  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
362
363  if( empty($_POST['login']) ||
364      empty($_POST['fullname']) ||
365      empty($_POST['email']) ){
366    msg($lang['regmissing'],-1);
367    return false;
368  }
369
370  //check mail
371  if(!mail_isvalid($_POST['email'])){
372    msg($lang['regbadmail'],-1);
373    return false;
374  }
375
376  //okay try to create the user
377  $pass = auth_createUser($_POST['login'],$_POST['fullname'],$_POST['email']);
378  if(empty($pass)){
379    msg($lang['reguexists'],-1);
380    return false;
381  }
382
383  //send him the password
384  if (auth_sendPassword($_POST['login'],$pass)){
385    msg($lang['regsuccess'],1);
386    return true;
387  }else{
388    msg($lang['regmailfail'],-1);
389    return false;
390  }
391}
392
393?>
394