xref: /dokuwiki/inc/auth.php (revision 87ddda95605ce63faf0e4a8ffff254354ea3dc66)
1<?
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  require_once("inc/common.php");
13  require_once("inc/io.php");
14  require_once("inc/blowfish.php");
15  // load the the auth functions
16  require_once('inc/auth_'.$conf['authtype'].'.php');
17
18  // some ACL level defines
19  define('AUTH_NONE',0);
20  define('AUTH_READ',1);
21  define('AUTH_EDIT',2);
22  define('AUTH_CREATE',4);
23  define('AUTH_UPLOAD',8);
24  define('AUTH_GRANT',255);
25
26  if($conf['useacl']){
27    auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
28    // load ACL into a global array
29    $AUTH_ACL = file('conf/acl.auth');
30  }
31
32/**
33 * This tries to login the user based on the sent auth credentials
34 *
35 * The authentication works like this: if a username was given
36 * a new login is assumed and user/password are checked. If they
37 * are correct the password is encrypted with blowfish and stored
38 * together with the username in a cookie - the same info is stored
39 * in the session, too. Additonally a browserID is stored in the
40 * session.
41 *
42 * If no username was given the cookie is checked: if the username,
43 * crypted password and browserID match between session and cookie
44 * no further testing is done and the user is accepted
45 *
46 * If a cookie was found but no session info was availabe the
47 * blowish encrypted password from the cookie is decrypted and
48 * together with username rechecked by calling this function again.
49 *
50 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
51 * are set.
52 *
53 * @author  Andreas Gohr <andi@splitbrain.org>
54 *
55 * @param   string  $user    Username
56 * @param   string  $pass    Cleartext Password
57 * @param   bool    $sticky  Cookie should not expire
58 * @return  bool             true on successful auth
59*/
60function auth_login($user,$pass,$sticky=false){
61  global $USERINFO;
62  global $conf;
63  global $lang;
64  $sticky ? $sticky = true : $sticky = false; //sanity check
65
66  if(isset($user)){
67    //usual login
68    if (auth_checkPass($user,$pass)){
69      // make logininfo globally available
70      $_SERVER['REMOTE_USER'] = $user;
71      $USERINFO = auth_getUserData($user); //FIXME move all references to session
72
73      // set cookie
74      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
75      $cookie = base64_encode("$user|$sticky|$pass");
76      if($sticky) $time = time()+60*60*24*365; //one year
77      setcookie('DokuWikiAUTH',$cookie,$time);
78
79      // set session
80      $_SESSION[$conf['title']]['auth']['user'] = $user;
81      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
82      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
83      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
84      return true;
85    }else{
86      //invalid credentials - log off
87      msg($lang['badlogin'],-1);
88      auth_logoff();
89      return false;
90    }
91  }else{
92    // read cookie information
93    $cookie = base64_decode($_COOKIE['DokuWikiAUTH']);
94    list($user,$sticky,$pass) = split('\|',$cookie,3);
95    // get session info
96    $session = $_SESSION[$conf['title']]['auth'];
97
98    if($user && $pass){
99      // we got a cookie - see if we can trust it
100      if(isset($session) &&
101        ($session['user'] == $user) &&
102        ($session['pass'] == $pass) &&  //still crypted
103        ($session['buid'] == auth_browseruid()) ){
104        // he has session, cookie and browser right - let him in
105        $_SERVER['REMOTE_USER'] = $user;
106        $USERINFO = $session['info']; //FIXME move all references to session
107        return true;
108      }
109      // no we don't trust it yet - recheck pass
110      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
111      return auth_login($user,$pass,$sticky);
112    }
113  }
114  //just to be sure
115  auth_logoff();
116  return false;
117}
118
119/**
120 * Builds a pseudo UID from browserdata
121 *
122 * This is neither unique nor unfakable - still it adds some
123 * security
124 *
125 * @author  Andreas Gohr <andi@splitbrain.org>
126 *
127 * @return  string  a MD5 sum of various browser headers
128 */
129function auth_browseruid(){
130  $uid  = '';
131  $uid .= $_SERVER['HTTP_USER_AGENT'];
132  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
133  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
134  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
135  return md5($uid);
136}
137
138/**
139 * Creates a random key to encrypt the password in cookies
140 *
141 * This function tries to read the password for encrypting
142 * cookies from $conf['datadir'].'/.cache/cookiesalt'
143 * if no such file is found a random key is created and
144 * and stored in this file.
145 *
146 * @author  Andreas Gohr <andi@splitbrain.org>
147 *
148 * @return  string
149 */
150function auth_cookiesalt(){
151  global $conf;
152  $file = $conf['datadir'].'/.cache/cookiesalt';
153  $salt = io_readFile($file);
154  if(empty($salt)){
155    $salt = uniqid(rand(),true);
156    io_saveFile($file,$salt);
157  }
158  return $salt;
159}
160
161/**
162 * This clears all authenticationdata and thus log the user
163 * off
164 *
165 * @author  Andreas Gohr <andi@splitbrain.org>
166 */
167function auth_logoff(){
168  global $conf;
169  global $USERINFO;
170  unset($_SESSION[$conf['title']]['auth']['user']);
171  unset($_SESSION[$conf['title']]['auth']['pass']);
172  unset($_SESSION[$conf['title']]['auth']['info']);
173  unset($_SERVER['REMOTE_USER']);
174  $USERINFO=null; //FIXME
175  setcookie('DokuWikiAUTH','',time()-3600);
176}
177
178/**
179 * Convinience function for auth_aclcheck()
180 *
181 * This checks the permissions for the current user
182 *
183 * @author  Andreas Gohr <andi@splitbrain.org>
184 *
185 * @param  string  $id  page ID
186 * @return int          permission level
187 */
188function auth_quickaclcheck($id){
189  global $conf;
190  global $USERINFO;
191  # if no ACL is used always return upload rights
192  if(!$conf['useacl']) return AUTH_UPLOAD;
193  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
194}
195
196/**
197 * Returns the maximum rights a user has for
198 * the given ID or its namespace
199 *
200 * @author  Andreas Gohr <andi@splitbrain.org>
201 *
202 * @param  string  $id     page ID
203 * @param  string  $user   Username
204 * @param  array   $groups Array of groups the user is in
205 * @return int             permission level
206 */
207function auth_aclcheck($id,$user,$groups){
208  global $conf;
209  global $AUTH_ACL;
210
211  # if no ACL is used always return upload rights
212  if(!$conf['useacl']) return AUTH_UPLOAD;
213
214  $ns    = getNS($id);
215  $perm  = -1;
216
217  if($user){
218    //prepend groups with @
219    for($i=0; $i<count($groups); $i++){
220      $groups[$i] = '@'.$groups[$i];
221    }
222    //add ALL group
223    $groups[] = '@ALL';
224    //add User
225    $groups[] = $user;
226    //build regexp
227    $regexp   = join('|',$groups);
228  }else{
229    $regexp = '@ALL';
230  }
231
232  //check exact match first
233  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
234  if(count($matches)){
235    foreach($matches as $match){
236      $match = preg_replace('/#.*$/','',$match); //ignore comments
237      $acl   = preg_split('/\s+/',$match);
238      if($acl[2] > $perm){
239        $perm = $acl[2];
240      }
241    }
242    if($perm > -1){
243      //we had a match - return it
244      return $perm;
245    }
246  }
247
248  //still here? do the namespace checks
249  if($ns){
250    $path = $ns.':\*';
251  }else{
252    $path = '\*'; //root document
253  }
254
255  do{
256    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
257    if(count($matches)){
258      foreach($matches as $match){
259        $match = preg_replace('/#.*$/','',$match); //ignore comments
260        $acl   = preg_split('/\s+/',$match);
261        if($acl[2] > $perm){
262          $perm = $acl[2];
263        }
264      }
265      //we had a match - return it
266      return $perm;
267    }
268
269    //get next higher namespace
270    $ns   = getNS($ns);
271
272    if($path != '\*'){
273      $path = $ns.':\*';
274      if($path == ':\*') $path = '\*';
275    }else{
276      //we did this already
277      //looks like there is something wrong with the ACL
278      //break here
279      return $perm;
280    }
281  }while(1); //this should never loop endless
282}
283
284/**
285 * Create a pronouncable password
286 *
287 * @author  Andreas Gohr <andi@splitbrain.org>
288 * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
289 *
290 * @return string  pronouncable password
291 */
292function auth_pwgen(){
293  $pw = '';
294  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
295  $v  = 'aeiou';              //vowels
296  $a  = $c.$v;                //both
297
298  //use two syllables...
299  for($i=0;$i < 2; $i++){
300    $pw .= $c[rand(0, strlen($c)-1)];
301    $pw .= $v[rand(0, strlen($v)-1)];
302    $pw .= $a[rand(0, strlen($a)-1)];
303  }
304  //... and add a nice number
305  $pw .= rand(10,99);
306
307  return $pw;
308}
309
310/**
311 * Sends a password to the given user
312 *
313 * @author  Andreas Gohr <andi@splitbrain.org>
314 *
315 * @return bool  true on success
316 */
317function auth_sendPassword($user,$password){
318  global $conf;
319  global $lang;
320  $hdrs  = '';
321  $userinfo = auth_getUserData($user);
322
323  if(!$userinfo['mail']) return false;
324
325  $text = rawLocale('password');
326  $text = str_replace('@DOKUWIKIURL@',getBaseURL(true),$text);
327  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
328  $text = str_replace('@LOGIN@',$user,$text);
329  $text = str_replace('@PASSWORD@',$password,$text);
330  $text = str_replace('@TITLE@',$conf['title'],$text);
331
332  if (!empty($conf['mailfrom'])) {
333    $hdrs = 'From: '.$conf['mailfrom']."\n";
334  }
335  return @mail($userinfo['mail'],$lang['regpwmail'],$text,$hdrs);
336}
337
338/**
339 * Register a new user
340 *
341 * This registers a new user - Data is read directly from $_POST
342 *
343 * @author  Andreas Gohr <andi@splitbrain.org>
344 *
345 * @return bool  true on success, false on any error
346 */
347function register(){
348  global $lang;
349  global $conf;
350
351  if(!$_POST['save']) return false;
352  if(!$conf['openregister']) return false;
353
354  //clean username
355  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
356  $_POST['login'] = cleanID($_POST['login']);
357  //clean fullname and email
358  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
359  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
360
361  if( empty($_POST['login']) ||
362      empty($_POST['fullname']) ||
363      empty($_POST['email']) ){
364    msg($lang['regmissing'],-1);
365    return false;
366  }
367
368  //check mail
369  if(!isvalidemail($_POST['email'])){
370    msg($lang['regbadmail'],-1);
371    return false;
372  }
373
374  //okay try to create the user
375  $pass = auth_createUser($_POST['login'],$_POST['fullname'],$_POST['email']);
376  if(empty($pass)){
377    msg($lang['reguexists'],-1);
378    return false;
379  }
380
381  //send him the password
382  if (auth_sendPassword($_POST['login'],$pass)){
383    msg($lang['regsuccess'],1);
384    return true;
385  }else{
386    msg($lang['regmailfail'],-1);
387    return false;
388  }
389}
390
391/**
392 * Uses a regular expresion to check if a given mail address is valid
393 *
394 * May not be completly RFC conform!
395 *
396 * @link    http://www.webmasterworld.com/forum88/135.htm
397 *
398 * @param   string $email the address to check
399 * @return  bool          true if address is valid
400 */
401function isvalidemail($email){
402  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
403}
404
405?>
406