xref: /dokuwiki/inc/auth.php (revision 1e866646d50b19b59ee9bc22a8c293a91c4e8176)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Authentication library
415fae107Sandi *
515fae107Sandi * Including this file will automatically try to login
615fae107Sandi * a user by calling auth_login()
715fae107Sandi *
815fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
915fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1015fae107Sandi */
1115fae107Sandi
12ed7b5f09Sandi  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
13ed7b5f09Sandi  require_once(DOKU_INC.'inc/common.php');
14ed7b5f09Sandi  require_once(DOKU_INC.'inc/io.php');
15ed7b5f09Sandi  require_once(DOKU_INC.'inc/blowfish.php');
16ed7b5f09Sandi  require_once(DOKU_INC.'inc/mail.php');
1715fae107Sandi  // load the the auth functions
18f62ea8a1Sandi  require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.php');
19f3f0262cSandi
20*1e866646Sandi  if (!defined('DOKU_COOKIE')) define('DOKU_COOKIE', 'DW'.md5($conf['title']));
21e65afed4SSameer D. Sahasrabuddhe
2215fae107Sandi  // some ACL level defines
23f3f0262cSandi  define('AUTH_NONE',0);
24f3f0262cSandi  define('AUTH_READ',1);
25f3f0262cSandi  define('AUTH_EDIT',2);
26f3f0262cSandi  define('AUTH_CREATE',4);
27f3f0262cSandi  define('AUTH_UPLOAD',8);
288ef6b7caSandi  define('AUTH_DELETE',16);
2910a76f6fSfrank  define('AUTH_ADMIN',255);
30f3f0262cSandi
31f3f0262cSandi  if($conf['useacl']){
32132bdbfeSandi    auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
3315fae107Sandi    //load ACL into a global array
3411799630Sandi    if(is_readable(DOKU_INC.'conf/acl.auth.php')){
35f62ea8a1Sandi      $AUTH_ACL = file(DOKU_INC.'conf/acl.auth.php');
3611799630Sandi    }else{
3711799630Sandi      $AUTH_ACL = array();
3811799630Sandi    }
39f3f0262cSandi  }
40f3f0262cSandi
41f3f0262cSandi/**
42f3f0262cSandi * This tries to login the user based on the sent auth credentials
43f3f0262cSandi *
44f3f0262cSandi * The authentication works like this: if a username was given
4515fae107Sandi * a new login is assumed and user/password are checked. If they
4615fae107Sandi * are correct the password is encrypted with blowfish and stored
4715fae107Sandi * together with the username in a cookie - the same info is stored
4815fae107Sandi * in the session, too. Additonally a browserID is stored in the
4915fae107Sandi * session.
5015fae107Sandi *
5115fae107Sandi * If no username was given the cookie is checked: if the username,
5215fae107Sandi * crypted password and browserID match between session and cookie
5315fae107Sandi * no further testing is done and the user is accepted
5415fae107Sandi *
5515fae107Sandi * If a cookie was found but no session info was availabe the
56136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
5715fae107Sandi * together with username rechecked by calling this function again.
58f3f0262cSandi *
59f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
60f3f0262cSandi * are set.
6115fae107Sandi *
6215fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
6315fae107Sandi *
6415fae107Sandi * @param   string  $user    Username
6515fae107Sandi * @param   string  $pass    Cleartext Password
6615fae107Sandi * @param   bool    $sticky  Cookie should not expire
6715fae107Sandi * @return  bool             true on successful auth
68f3f0262cSandi*/
69132bdbfeSandifunction auth_login($user,$pass,$sticky=false){
70f3f0262cSandi  global $USERINFO;
71f3f0262cSandi  global $conf;
72f3f0262cSandi  global $lang;
73132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
74f3f0262cSandi
75f3f0262cSandi  if(isset($user)){
76132bdbfeSandi    //usual login
77f3f0262cSandi    if (auth_checkPass($user,$pass)){
78132bdbfeSandi      // make logininfo globally available
79f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
80132bdbfeSandi      $USERINFO = auth_getUserData($user); //FIXME move all references to session
81132bdbfeSandi
82132bdbfeSandi      // set cookie
83132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
84132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
85132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
86e65afed4SSameer D. Sahasrabuddhe      setcookie(DOKU_COOKIE,$cookie,$time,'/');
87132bdbfeSandi
88132bdbfeSandi      // set session
89132bdbfeSandi      $_SESSION[$conf['title']]['auth']['user'] = $user;
90132bdbfeSandi      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
91132bdbfeSandi      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
92132bdbfeSandi      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
93132bdbfeSandi      return true;
94f3f0262cSandi    }else{
95f3f0262cSandi      //invalid credentials - log off
96f3f0262cSandi      msg($lang['badlogin'],-1);
97f3f0262cSandi      auth_logoff();
98132bdbfeSandi      return false;
99f3f0262cSandi    }
100f3f0262cSandi  }else{
101132bdbfeSandi    // read cookie information
102e65afed4SSameer D. Sahasrabuddhe    $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
103132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
104132bdbfeSandi    // get session info
105132bdbfeSandi    $session = $_SESSION[$conf['title']]['auth'];
106132bdbfeSandi
107132bdbfeSandi    if($user && $pass){
108132bdbfeSandi      // we got a cookie - see if we can trust it
109132bdbfeSandi      if(isset($session) &&
110132bdbfeSandi        ($session['user'] == $user) &&
111132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
112132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
113132bdbfeSandi        // he has session, cookie and browser right - let him in
114132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
115132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
116132bdbfeSandi        return true;
117132bdbfeSandi      }
118132bdbfeSandi      // no we don't trust it yet - recheck pass
119132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
120132bdbfeSandi      return auth_login($user,$pass,$sticky);
121132bdbfeSandi    }
122132bdbfeSandi  }
123f3f0262cSandi  //just to be sure
124f3f0262cSandi  auth_logoff();
125132bdbfeSandi  return false;
126f3f0262cSandi}
127132bdbfeSandi
128132bdbfeSandi/**
129136ce040Sandi * Builds a pseudo UID from browser and IP data
130132bdbfeSandi *
131132bdbfeSandi * This is neither unique nor unfakable - still it adds some
132136ce040Sandi * security. Using the first part of the IP makes sure
133136ce040Sandi * proxy farms like AOLs are stil okay.
13415fae107Sandi *
13515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
13615fae107Sandi *
13715fae107Sandi * @return  string  a MD5 sum of various browser headers
138132bdbfeSandi */
139132bdbfeSandifunction auth_browseruid(){
140132bdbfeSandi  $uid  = '';
141132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
142132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
143132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
144132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
145136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
146132bdbfeSandi  return md5($uid);
147132bdbfeSandi}
148132bdbfeSandi
149132bdbfeSandi/**
150132bdbfeSandi * Creates a random key to encrypt the password in cookies
15115fae107Sandi *
15215fae107Sandi * This function tries to read the password for encrypting
15398407a7aSandi * cookies from $conf['metadir'].'/_htcookiesalt'
15415fae107Sandi * if no such file is found a random key is created and
15515fae107Sandi * and stored in this file.
15615fae107Sandi *
15715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
15815fae107Sandi *
15915fae107Sandi * @return  string
160132bdbfeSandi */
161132bdbfeSandifunction auth_cookiesalt(){
162132bdbfeSandi  global $conf;
16398407a7aSandi  $file = $conf['metadir'].'/_htcookiesalt';
164132bdbfeSandi  $salt = io_readFile($file);
165132bdbfeSandi  if(empty($salt)){
166132bdbfeSandi    $salt = uniqid(rand(),true);
167132bdbfeSandi    io_saveFile($file,$salt);
168132bdbfeSandi  }
169132bdbfeSandi  return $salt;
170f3f0262cSandi}
171f3f0262cSandi
172f3f0262cSandi/**
173f3f0262cSandi * This clears all authenticationdata and thus log the user
174f3f0262cSandi * off
17515fae107Sandi *
17615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
177f3f0262cSandi */
178f3f0262cSandifunction auth_logoff(){
179f3f0262cSandi  global $conf;
180f3f0262cSandi  global $USERINFO;
181132bdbfeSandi  unset($_SESSION[$conf['title']]['auth']['user']);
182132bdbfeSandi  unset($_SESSION[$conf['title']]['auth']['pass']);
183132bdbfeSandi  unset($_SESSION[$conf['title']]['auth']['info']);
184f3f0262cSandi  unset($_SERVER['REMOTE_USER']);
185132bdbfeSandi  $USERINFO=null; //FIXME
186*1e866646Sandi  setcookie(DOKU_COOKIE,'',time()-600000,'/');
187f3f0262cSandi}
188f3f0262cSandi
189f3f0262cSandi/**
19015fae107Sandi * Convinience function for auth_aclcheck()
19115fae107Sandi *
19215fae107Sandi * This checks the permissions for the current user
19315fae107Sandi *
19415fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
19515fae107Sandi *
19615fae107Sandi * @param  string  $id  page ID
19715fae107Sandi * @return int          permission level
198f3f0262cSandi */
199f3f0262cSandifunction auth_quickaclcheck($id){
200f3f0262cSandi  global $conf;
201f3f0262cSandi  global $USERINFO;
202f3f0262cSandi  # if no ACL is used always return upload rights
203f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
204f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
205f3f0262cSandi}
206f3f0262cSandi
207f3f0262cSandi/**
208f3f0262cSandi * Returns the maximum rights a user has for
209f3f0262cSandi * the given ID or its namespace
21015fae107Sandi *
21115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
21215fae107Sandi *
21315fae107Sandi * @param  string  $id     page ID
21415fae107Sandi * @param  string  $user   Username
21515fae107Sandi * @param  array   $groups Array of groups the user is in
21615fae107Sandi * @return int             permission level
217f3f0262cSandi */
218f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
219f3f0262cSandi  global $conf;
220f3f0262cSandi  global $AUTH_ACL;
221f3f0262cSandi
222f3f0262cSandi  # if no ACL is used always return upload rights
223f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
224f3f0262cSandi
22510a76f6fSfrank  //if user is superuser return 255 (acl_admin)
22610a76f6fSfrank  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
22710a76f6fSfrank
228074cf26bSandi  //make sure groups is an array
229074cf26bSandi  if(!is_array($groups)) $groups = array();
230074cf26bSandi
23110a76f6fSfrank  //prepend groups with @
2322cd2db38Sandi  $cnt = count($groups);
2332cd2db38Sandi  for($i=0; $i<$cnt; $i++){
23410a76f6fSfrank    $groups[$i] = '@'.$groups[$i];
23510a76f6fSfrank  }
23610a76f6fSfrank  //if user is in superuser group return 255 (acl_admin)
23710a76f6fSfrank  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
23810a76f6fSfrank
239f3f0262cSandi  $ns    = getNS($id);
240f3f0262cSandi  $perm  = -1;
241f3f0262cSandi
242f3f0262cSandi  if($user){
243f3f0262cSandi    //add ALL group
244f3f0262cSandi    $groups[] = '@ALL';
245f3f0262cSandi    //add User
246f3f0262cSandi    $groups[] = $user;
247f3f0262cSandi    //build regexp
248f3f0262cSandi    $regexp   = join('|',$groups);
249f3f0262cSandi  }else{
250f3f0262cSandi    $regexp = '@ALL';
251f3f0262cSandi  }
252f3f0262cSandi
253f3f0262cSandi  //check exact match first
254f3f0262cSandi  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
255f3f0262cSandi  if(count($matches)){
256f3f0262cSandi    foreach($matches as $match){
257f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
258f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
2598ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
260f3f0262cSandi      if($acl[2] > $perm){
261f3f0262cSandi        $perm = $acl[2];
262f3f0262cSandi      }
263f3f0262cSandi    }
264f3f0262cSandi    if($perm > -1){
265f3f0262cSandi      //we had a match - return it
266f3f0262cSandi      return $perm;
267f3f0262cSandi    }
268f3f0262cSandi  }
269f3f0262cSandi
270f3f0262cSandi  //still here? do the namespace checks
271f3f0262cSandi  if($ns){
272f3f0262cSandi    $path = $ns.':\*';
273f3f0262cSandi  }else{
274f3f0262cSandi    $path = '\*'; //root document
275f3f0262cSandi  }
276f3f0262cSandi
277f3f0262cSandi  do{
278f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
279f3f0262cSandi    if(count($matches)){
280f3f0262cSandi      foreach($matches as $match){
281f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
282f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
2838ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
284f3f0262cSandi        if($acl[2] > $perm){
285f3f0262cSandi          $perm = $acl[2];
286f3f0262cSandi        }
287f3f0262cSandi      }
288f3f0262cSandi      //we had a match - return it
289f3f0262cSandi      return $perm;
290f3f0262cSandi    }
291f3f0262cSandi
292f3f0262cSandi    //get next higher namespace
293f3f0262cSandi    $ns   = getNS($ns);
294f3f0262cSandi
295f3f0262cSandi    if($path != '\*'){
296f3f0262cSandi      $path = $ns.':\*';
297f3f0262cSandi      if($path == ':\*') $path = '\*';
298f3f0262cSandi    }else{
299f3f0262cSandi      //we did this already
300f3f0262cSandi      //looks like there is something wrong with the ACL
301f3f0262cSandi      //break here
302f3f0262cSandi      return $perm;
303f3f0262cSandi    }
304f3f0262cSandi  }while(1); //this should never loop endless
30552a5af8dSandi
30652a5af8dSandi  //still here? return no permissions
30752a5af8dSandi  return AUTH_NONE;
308f3f0262cSandi}
309f3f0262cSandi
310f3f0262cSandi/**
311f3f0262cSandi * Create a pronouncable password
312f3f0262cSandi *
31315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
31415fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
31515fae107Sandi *
31615fae107Sandi * @return string  pronouncable password
317f3f0262cSandi */
318f3f0262cSandifunction auth_pwgen(){
319f3f0262cSandi  $pw = '';
320f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
321f3f0262cSandi  $v  = 'aeiou';              //vowels
322f3f0262cSandi  $a  = $c.$v;                //both
323f3f0262cSandi
324f3f0262cSandi  //use two syllables...
325f3f0262cSandi  for($i=0;$i < 2; $i++){
326f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
327f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
328f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
329f3f0262cSandi  }
330f3f0262cSandi  //... and add a nice number
331f3f0262cSandi  $pw .= rand(10,99);
332f3f0262cSandi
333f3f0262cSandi  return $pw;
334f3f0262cSandi}
335f3f0262cSandi
336f3f0262cSandi/**
337f3f0262cSandi * Sends a password to the given user
338f3f0262cSandi *
33915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
34015fae107Sandi *
34115fae107Sandi * @return bool  true on success
342f3f0262cSandi */
343f3f0262cSandifunction auth_sendPassword($user,$password){
344f3f0262cSandi  global $conf;
345f3f0262cSandi  global $lang;
346f3f0262cSandi  $hdrs  = '';
34787ddda95Sandi  $userinfo = auth_getUserData($user);
348f3f0262cSandi
34987ddda95Sandi  if(!$userinfo['mail']) return false;
350f3f0262cSandi
351f3f0262cSandi  $text = rawLocale('password');
352ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
35387ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
354f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
355f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
356f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
357f3f0262cSandi
35844f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
35944f669e9Sandi                   $lang['regpwmail'],
36044f669e9Sandi                   $text,
36144f669e9Sandi                   $conf['mailfrom']);
362f3f0262cSandi}
363f3f0262cSandi
364f3f0262cSandi/**
36515fae107Sandi * Register a new user
366f3f0262cSandi *
36715fae107Sandi * This registers a new user - Data is read directly from $_POST
36815fae107Sandi *
36915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
37015fae107Sandi *
37115fae107Sandi * @return bool  true on success, false on any error
372f3f0262cSandi */
373f3f0262cSandifunction register(){
374f3f0262cSandi  global $lang;
375eb5d07e4Sjan  global $conf;
376f3f0262cSandi
377f3f0262cSandi  if(!$_POST['save']) return false;
378640145a5Sandi
379f3f0262cSandi  //clean username
380f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
381f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
382f3f0262cSandi  //clean fullname and email
383f3f0262cSandi  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
384f3f0262cSandi  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
385f3f0262cSandi
386f3f0262cSandi  if( empty($_POST['login']) ||
387f3f0262cSandi      empty($_POST['fullname']) ||
388f3f0262cSandi      empty($_POST['email']) ){
389f3f0262cSandi    msg($lang['regmissing'],-1);
390f3f0262cSandi    return false;
391f3f0262cSandi  }
392f3f0262cSandi
393cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
394cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
395cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
396cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
397bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
398cab2716aSmatthias.grimm    return false;
399cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
400bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
401cab2716aSmatthias.grimm    return false;
402cab2716aSmatthias.grimm  } else {
403cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
404cab2716aSmatthias.grimm  }
405cab2716aSmatthias.grimm
406f3f0262cSandi  //check mail
40744f669e9Sandi  if(!mail_isvalid($_POST['email'])){
408f3f0262cSandi    msg($lang['regbadmail'],-1);
409f3f0262cSandi    return false;
410f3f0262cSandi  }
411f3f0262cSandi
412f3f0262cSandi  //okay try to create the user
4137c37db8aSmatthias.grimm  $pass = auth_createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email']);
414f3f0262cSandi  if(empty($pass)){
415f3f0262cSandi    msg($lang['reguexists'],-1);
416f3f0262cSandi    return false;
417f3f0262cSandi  }
418f3f0262cSandi
419cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
420cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
421cab2716aSmatthias.grimm    return true;
422cab2716aSmatthias.grimm  }
423cab2716aSmatthias.grimm
424cab2716aSmatthias.grimm  // autogenerated password? then send him the password
425f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
426f3f0262cSandi    msg($lang['regsuccess'],1);
427f3f0262cSandi    return true;
428f3f0262cSandi  }else{
429f3f0262cSandi    msg($lang['regmailfail'],-1);
430f3f0262cSandi    return false;
431f3f0262cSandi  }
432f3f0262cSandi}
433f3f0262cSandi
43410a76f6fSfrank/**
43510a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
43610a76f6fSfrank *
43710a76f6fSfrank * May not be completly RFC conform!
43810a76f6fSfrank *
43910a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
44010a76f6fSfrank *
44110a76f6fSfrank * @param   string $email the address to check
44210a76f6fSfrank * @return  bool          true if address is valid
44310a76f6fSfrank */
44410a76f6fSfrankfunction isvalidemail($email){
44510a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
44610a76f6fSfrank}
44710a76f6fSfrank
448b0855b11Sandi/**
449b0855b11Sandi * Encrypts a password using the given method and salt
450b0855b11Sandi *
451b0855b11Sandi * If the selected method needs a salt and none was given, a random one
452b0855b11Sandi * is chosen.
453b0855b11Sandi *
454b0855b11Sandi * The following methods are understood:
455b0855b11Sandi *
456b0855b11Sandi *   smd5  - Salted MD5 hashing
457b0855b11Sandi *   md5   - Simple MD5 hashing
458b0855b11Sandi *   sha1  - SHA1 hashing
459b0855b11Sandi *   ssha  - Salted SHA1 hashing
460d7be6245Sandi *   crypt - Unix crypt
461d7be6245Sandi *   mysql - MySQL password (old method)
462d7be6245Sandi *   my411 - MySQL 4.1.1 password
463b0855b11Sandi *
464b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
465b0855b11Sandi * @return  string  The crypted password
466b0855b11Sandi */
467b0855b11Sandifunction auth_cryptPassword($clear,$method='',$salt=''){
468b0855b11Sandi  global $conf;
469b0855b11Sandi  if(empty($method)) $method = $conf['passcrypt'];
47010a76f6fSfrank
471b0855b11Sandi  //prepare a salt
472b0855b11Sandi  if(empty($salt)) $salt = md5(uniqid(rand(), true));
473b0855b11Sandi
474b0855b11Sandi  switch(strtolower($method)){
475b0855b11Sandi    case 'smd5':
476b0855b11Sandi        return crypt($clear,'$1$'.substr($salt,0,8).'$');
477b0855b11Sandi    case 'md5':
478b0855b11Sandi      return md5($clear);
479b0855b11Sandi    case 'sha1':
480b0855b11Sandi      return sha1($clear);
481b0855b11Sandi    case 'ssha':
482b0855b11Sandi      $salt=substr($salt,0,4);
483d6e54e02Smatthiasgrimm      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
484b0855b11Sandi    case 'crypt':
485b0855b11Sandi      return crypt($clear,substr($salt,0,2));
486d7be6245Sandi    case 'mysql':
487d7be6245Sandi      //from http://www.php.net/mysql comment by <soren at byu dot edu>
488d7be6245Sandi      $nr=0x50305735;
489d7be6245Sandi      $nr2=0x12345671;
490d7be6245Sandi      $add=7;
491d7be6245Sandi      $charArr = preg_split("//", $clear);
492d7be6245Sandi      foreach ($charArr as $char) {
493d7be6245Sandi        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
494d7be6245Sandi        $charVal = ord($char);
495d7be6245Sandi        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
496d7be6245Sandi        $nr2 += ($nr2 << 8) ^ $nr;
497d7be6245Sandi        $add += $charVal;
498d7be6245Sandi      }
499d7be6245Sandi      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
500d7be6245Sandi    case 'my411':
501d7be6245Sandi      return '*'.sha1(pack("H*", sha1($clear)));
502b0855b11Sandi    default:
503b0855b11Sandi      msg("Unsupported crypt method $method",-1);
504b0855b11Sandi  }
505b0855b11Sandi}
506b0855b11Sandi
507b0855b11Sandi/**
508b0855b11Sandi * Verifies a cleartext password against a crypted hash
509b0855b11Sandi *
510b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
511b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
512b0855b11Sandi * match true is is returned else false
513b0855b11Sandi *
514b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
515b0855b11Sandi * @return  bool
516b0855b11Sandi */
517b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
518b0855b11Sandi  $method='';
519b0855b11Sandi  $salt='';
520b0855b11Sandi
521b0855b11Sandi  //determine the used method and salt
522d7be6245Sandi  $len = strlen($crypt);
523b0855b11Sandi  if(substr($crypt,0,3) == '$1$'){
524b0855b11Sandi    $method = 'smd5';
525b0855b11Sandi    $salt   = substr($crypt,3,8);
526b0855b11Sandi  }elseif(substr($crypt,0,6) == '{SSHA}'){
527b0855b11Sandi    $method = 'ssha';
528b0855b11Sandi    $salt   = substr(base64_decode(substr($crypt, 6)),20);
529d7be6245Sandi  }elseif($len == 32){
530b0855b11Sandi    $method = 'md5';
531d7be6245Sandi  }elseif($len == 40){
532b0855b11Sandi    $method = 'sha1';
533d7be6245Sandi  }elseif($len == 16){
534d7be6245Sandi    $method = 'mysql';
535d7be6245Sandi  }elseif($len == 41 && $crypt[0] == '*'){
536d7be6245Sandi    $method = 'my411';
537b0855b11Sandi  }else{
538b0855b11Sandi    $method = 'crypt';
539b0855b11Sandi    $salt   = substr($crypt,0,2);
540b0855b11Sandi  }
541b0855b11Sandi
542b0855b11Sandi  //crypt and compare
543b0855b11Sandi  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
544b0855b11Sandi    return true;
545b0855b11Sandi  }
546b0855b11Sandi  return false;
547b0855b11Sandi}
548340756e4Sandi
549340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
550