xref: /dokuwiki/inc/auth.php (revision 10a76f6fd45bbbf4443fb8626d35aae3a388c490)
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  require_once(DOKU_INC.'inc/acl_admin.php');
20
21  // some ACL level defines
22  define('AUTH_NONE',0);
23  define('AUTH_READ',1);
24  define('AUTH_EDIT',2);
25  define('AUTH_CREATE',4);
26  define('AUTH_UPLOAD',8);
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    $AUTH_ACL = file('conf/acl.auth');
33  }
34
35/**
36 * This tries to login the user based on the sent auth credentials
37 *
38 * The authentication works like this: if a username was given
39 * a new login is assumed and user/password are checked. If they
40 * are correct the password is encrypted with blowfish and stored
41 * together with the username in a cookie - the same info is stored
42 * in the session, too. Additonally a browserID is stored in the
43 * session.
44 *
45 * If no username was given the cookie is checked: if the username,
46 * crypted password and browserID match between session and cookie
47 * no further testing is done and the user is accepted
48 *
49 * If a cookie was found but no session info was availabe the
50 * blowish encrypted password from the cookie is decrypted and
51 * together with username rechecked by calling this function again.
52 *
53 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
54 * are set.
55 *
56 * @author  Andreas Gohr <andi@splitbrain.org>
57 *
58 * @param   string  $user    Username
59 * @param   string  $pass    Cleartext Password
60 * @param   bool    $sticky  Cookie should not expire
61 * @return  bool             true on successful auth
62*/
63function auth_login($user,$pass,$sticky=false){
64  global $USERINFO;
65  global $conf;
66  global $lang;
67  $sticky ? $sticky = true : $sticky = false; //sanity check
68
69  if(isset($user)){
70    //usual login
71    if (auth_checkPass($user,$pass)){
72      // make logininfo globally available
73      $_SERVER['REMOTE_USER'] = $user;
74      $USERINFO = auth_getUserData($user); //FIXME move all references to session
75
76      // set cookie
77      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
78      $cookie = base64_encode("$user|$sticky|$pass");
79      if($sticky) $time = time()+60*60*24*365; //one year
80      setcookie('DokuWikiAUTH',$cookie,$time);
81
82      // set session
83      $_SESSION[$conf['title']]['auth']['user'] = $user;
84      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
85      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
86      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
87      return true;
88    }else{
89      //invalid credentials - log off
90      msg($lang['badlogin'],-1);
91      auth_logoff();
92      return false;
93    }
94  }else{
95    // read cookie information
96    $cookie = base64_decode($_COOKIE['DokuWikiAUTH']);
97    list($user,$sticky,$pass) = split('\|',$cookie,3);
98    // get session info
99    $session = $_SESSION[$conf['title']]['auth'];
100
101    if($user && $pass){
102      // we got a cookie - see if we can trust it
103      if(isset($session) &&
104        ($session['user'] == $user) &&
105        ($session['pass'] == $pass) &&  //still crypted
106        ($session['buid'] == auth_browseruid()) ){
107        // he has session, cookie and browser right - let him in
108        $_SERVER['REMOTE_USER'] = $user;
109        $USERINFO = $session['info']; //FIXME move all references to session
110        return true;
111      }
112      // no we don't trust it yet - recheck pass
113      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
114      return auth_login($user,$pass,$sticky);
115    }
116  }
117  //just to be sure
118  auth_logoff();
119  return false;
120}
121
122/**
123 * Builds a pseudo UID from browserdata
124 *
125 * This is neither unique nor unfakable - still it adds some
126 * security
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  return md5($uid);
139}
140
141/**
142 * Creates a random key to encrypt the password in cookies
143 *
144 * This function tries to read the password for encrypting
145 * cookies from $conf['datadir'].'/.cache/.htcookiesalt'
146 * if no such file is found a random key is created and
147 * and stored in this file.
148 *
149 * @author  Andreas Gohr <andi@splitbrain.org>
150 *
151 * @return  string
152 */
153function auth_cookiesalt(){
154  global $conf;
155  $file = $conf['datadir'].'/.cache/.htcookiesalt';
156  $salt = io_readFile($file);
157  if(empty($salt)){
158    $salt = uniqid(rand(),true);
159    io_saveFile($file,$salt);
160  }
161  return $salt;
162}
163
164/**
165 * This clears all authenticationdata and thus log the user
166 * off
167 *
168 * @author  Andreas Gohr <andi@splitbrain.org>
169 */
170function auth_logoff(){
171  global $conf;
172  global $USERINFO;
173  unset($_SESSION[$conf['title']]['auth']['user']);
174  unset($_SESSION[$conf['title']]['auth']['pass']);
175  unset($_SESSION[$conf['title']]['auth']['info']);
176  unset($_SERVER['REMOTE_USER']);
177  $USERINFO=null; //FIXME
178  setcookie('DokuWikiAUTH','',time()-3600);
179}
180
181/**
182 * Convinience function for auth_aclcheck()
183 *
184 * This checks the permissions for the current user
185 *
186 * @author  Andreas Gohr <andi@splitbrain.org>
187 *
188 * @param  string  $id  page ID
189 * @return int          permission level
190 */
191function auth_quickaclcheck($id){
192  global $conf;
193  global $USERINFO;
194  # if no ACL is used always return upload rights
195  if(!$conf['useacl']) return AUTH_UPLOAD;
196  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
197}
198
199/**
200 * Returns the maximum rights a user has for
201 * the given ID or its namespace
202 *
203 * @author  Andreas Gohr <andi@splitbrain.org>
204 *
205 * @param  string  $id     page ID
206 * @param  string  $user   Username
207 * @param  array   $groups Array of groups the user is in
208 * @return int             permission level
209 */
210function auth_aclcheck($id,$user,$groups){
211  global $conf;
212  global $AUTH_ACL;
213
214  # if no ACL is used always return upload rights
215  if(!$conf['useacl']) return AUTH_UPLOAD;
216
217  //if user is superuser return 255 (acl_admin)
218  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
219
220  //prepend groups with @
221  for($i=0; $i<count($groups); $i++){
222    $groups[$i] = '@'.$groups[$i];
223  }
224  //if user is in superuser group return 255 (acl_admin)
225  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
226
227  $ns    = getNS($id);
228  $perm  = -1;
229
230  if($user){
231    //prepend groups with @
232    for($i=0; $i<count($groups); $i++){
233      $groups[$i] = '@'.$groups[$i];
234    }
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