xref: /dokuwiki/inc/auth.php (revision f62ea8a1d1cf10eddeae777b11420624e111b7ea)
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
18*f62ea8a1Sandi  require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.php');
19f3f0262cSandi
2015fae107Sandi  // some ACL level defines
21f3f0262cSandi  define('AUTH_NONE',0);
22f3f0262cSandi  define('AUTH_READ',1);
23f3f0262cSandi  define('AUTH_EDIT',2);
24f3f0262cSandi  define('AUTH_CREATE',4);
25f3f0262cSandi  define('AUTH_UPLOAD',8);
268ef6b7caSandi  define('AUTH_DELETE',16);
2710a76f6fSfrank  define('AUTH_ADMIN',255);
28f3f0262cSandi
29f3f0262cSandi  if($conf['useacl']){
30132bdbfeSandi    auth_login($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
3115fae107Sandi    //load ACL into a global array
32*f62ea8a1Sandi    $AUTH_ACL = file(DOKU_INC.'conf/acl.auth.php');
33f3f0262cSandi  }
34f3f0262cSandi
35f3f0262cSandi/**
36f3f0262cSandi * This tries to login the user based on the sent auth credentials
37f3f0262cSandi *
38f3f0262cSandi * The authentication works like this: if a username was given
3915fae107Sandi * a new login is assumed and user/password are checked. If they
4015fae107Sandi * are correct the password is encrypted with blowfish and stored
4115fae107Sandi * together with the username in a cookie - the same info is stored
4215fae107Sandi * in the session, too. Additonally a browserID is stored in the
4315fae107Sandi * session.
4415fae107Sandi *
4515fae107Sandi * If no username was given the cookie is checked: if the username,
4615fae107Sandi * crypted password and browserID match between session and cookie
4715fae107Sandi * no further testing is done and the user is accepted
4815fae107Sandi *
4915fae107Sandi * If a cookie was found but no session info was availabe the
50136ce040Sandi * blowfish encrypted password from the cookie is decrypted and
5115fae107Sandi * together with username rechecked by calling this function again.
52f3f0262cSandi *
53f3f0262cSandi * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
54f3f0262cSandi * are set.
5515fae107Sandi *
5615fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
5715fae107Sandi *
5815fae107Sandi * @param   string  $user    Username
5915fae107Sandi * @param   string  $pass    Cleartext Password
6015fae107Sandi * @param   bool    $sticky  Cookie should not expire
6115fae107Sandi * @return  bool             true on successful auth
62f3f0262cSandi*/
63132bdbfeSandifunction auth_login($user,$pass,$sticky=false){
64f3f0262cSandi  global $USERINFO;
65f3f0262cSandi  global $conf;
66f3f0262cSandi  global $lang;
67132bdbfeSandi  $sticky ? $sticky = true : $sticky = false; //sanity check
68f3f0262cSandi
69f3f0262cSandi  if(isset($user)){
70132bdbfeSandi    //usual login
71f3f0262cSandi    if (auth_checkPass($user,$pass)){
72132bdbfeSandi      // make logininfo globally available
73f3f0262cSandi      $_SERVER['REMOTE_USER'] = $user;
74132bdbfeSandi      $USERINFO = auth_getUserData($user); //FIXME move all references to session
75132bdbfeSandi
76132bdbfeSandi      // set cookie
77132bdbfeSandi      $pass   = PMA_blowfish_encrypt($pass,auth_cookiesalt());
78132bdbfeSandi      $cookie = base64_encode("$user|$sticky|$pass");
79132bdbfeSandi      if($sticky) $time = time()+60*60*24*365; //one year
807009a5a9Sandi      setcookie('DokuWikiAUTH',$cookie,$time,'/');
81132bdbfeSandi
82132bdbfeSandi      // set session
83132bdbfeSandi      $_SESSION[$conf['title']]['auth']['user'] = $user;
84132bdbfeSandi      $_SESSION[$conf['title']]['auth']['pass'] = $pass;
85132bdbfeSandi      $_SESSION[$conf['title']]['auth']['buid'] = auth_browseruid();
86132bdbfeSandi      $_SESSION[$conf['title']]['auth']['info'] = $USERINFO;
87132bdbfeSandi      return true;
88f3f0262cSandi    }else{
89f3f0262cSandi      //invalid credentials - log off
90f3f0262cSandi      msg($lang['badlogin'],-1);
91f3f0262cSandi      auth_logoff();
92132bdbfeSandi      return false;
93f3f0262cSandi    }
94f3f0262cSandi  }else{
95132bdbfeSandi    // read cookie information
96132bdbfeSandi    $cookie = base64_decode($_COOKIE['DokuWikiAUTH']);
97132bdbfeSandi    list($user,$sticky,$pass) = split('\|',$cookie,3);
98132bdbfeSandi    // get session info
99132bdbfeSandi    $session = $_SESSION[$conf['title']]['auth'];
100132bdbfeSandi
101132bdbfeSandi    if($user && $pass){
102132bdbfeSandi      // we got a cookie - see if we can trust it
103132bdbfeSandi      if(isset($session) &&
104132bdbfeSandi        ($session['user'] == $user) &&
105132bdbfeSandi        ($session['pass'] == $pass) &&  //still crypted
106132bdbfeSandi        ($session['buid'] == auth_browseruid()) ){
107132bdbfeSandi        // he has session, cookie and browser right - let him in
108132bdbfeSandi        $_SERVER['REMOTE_USER'] = $user;
109132bdbfeSandi        $USERINFO = $session['info']; //FIXME move all references to session
110132bdbfeSandi        return true;
111132bdbfeSandi      }
112132bdbfeSandi      // no we don't trust it yet - recheck pass
113132bdbfeSandi      $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
114132bdbfeSandi      return auth_login($user,$pass,$sticky);
115132bdbfeSandi    }
116132bdbfeSandi  }
117f3f0262cSandi  //just to be sure
118f3f0262cSandi  auth_logoff();
119132bdbfeSandi  return false;
120f3f0262cSandi}
121132bdbfeSandi
122132bdbfeSandi/**
123136ce040Sandi * Builds a pseudo UID from browser and IP data
124132bdbfeSandi *
125132bdbfeSandi * This is neither unique nor unfakable - still it adds some
126136ce040Sandi * security. Using the first part of the IP makes sure
127136ce040Sandi * proxy farms like AOLs are stil okay.
12815fae107Sandi *
12915fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
13015fae107Sandi *
13115fae107Sandi * @return  string  a MD5 sum of various browser headers
132132bdbfeSandi */
133132bdbfeSandifunction auth_browseruid(){
134132bdbfeSandi  $uid  = '';
135132bdbfeSandi  $uid .= $_SERVER['HTTP_USER_AGENT'];
136132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
137132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
138132bdbfeSandi  $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
139136ce040Sandi  $uid .= substr($_SERVER['REMOTE_ADDR'],0,strpos($_SERVER['REMOTE_ADDR'],'.'));
140132bdbfeSandi  return md5($uid);
141132bdbfeSandi}
142132bdbfeSandi
143132bdbfeSandi/**
144132bdbfeSandi * Creates a random key to encrypt the password in cookies
14515fae107Sandi *
14615fae107Sandi * This function tries to read the password for encrypting
1479afe4dbfSjan * cookies from $conf['datadir'].'/_cache/_htcookiesalt'
14815fae107Sandi * if no such file is found a random key is created and
14915fae107Sandi * and stored in this file.
15015fae107Sandi *
15115fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
15215fae107Sandi *
15315fae107Sandi * @return  string
154132bdbfeSandi */
155132bdbfeSandifunction auth_cookiesalt(){
156132bdbfeSandi  global $conf;
1579afe4dbfSjan  $file = $conf['datadir'].'/_cache/_htcookiesalt';
158132bdbfeSandi  $salt = io_readFile($file);
159132bdbfeSandi  if(empty($salt)){
160132bdbfeSandi    $salt = uniqid(rand(),true);
161132bdbfeSandi    io_saveFile($file,$salt);
162132bdbfeSandi  }
163132bdbfeSandi  return $salt;
164f3f0262cSandi}
165f3f0262cSandi
166f3f0262cSandi/**
167f3f0262cSandi * This clears all authenticationdata and thus log the user
168f3f0262cSandi * off
16915fae107Sandi *
17015fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
171f3f0262cSandi */
172f3f0262cSandifunction auth_logoff(){
173f3f0262cSandi  global $conf;
174f3f0262cSandi  global $USERINFO;
175132bdbfeSandi  unset($_SESSION[$conf['title']]['auth']['user']);
176132bdbfeSandi  unset($_SESSION[$conf['title']]['auth']['pass']);
177132bdbfeSandi  unset($_SESSION[$conf['title']]['auth']['info']);
178f3f0262cSandi  unset($_SERVER['REMOTE_USER']);
179132bdbfeSandi  $USERINFO=null; //FIXME
1807009a5a9Sandi  setcookie('DokuWikiAUTH','',time()-600000,'/');
181f3f0262cSandi}
182f3f0262cSandi
183f3f0262cSandi/**
18415fae107Sandi * Convinience function for auth_aclcheck()
18515fae107Sandi *
18615fae107Sandi * This checks the permissions for the current user
18715fae107Sandi *
18815fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
18915fae107Sandi *
19015fae107Sandi * @param  string  $id  page ID
19115fae107Sandi * @return int          permission level
192f3f0262cSandi */
193f3f0262cSandifunction auth_quickaclcheck($id){
194f3f0262cSandi  global $conf;
195f3f0262cSandi  global $USERINFO;
196f3f0262cSandi  # if no ACL is used always return upload rights
197f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
198f3f0262cSandi  return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
199f3f0262cSandi}
200f3f0262cSandi
201f3f0262cSandi/**
202f3f0262cSandi * Returns the maximum rights a user has for
203f3f0262cSandi * the given ID or its namespace
20415fae107Sandi *
20515fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
20615fae107Sandi *
20715fae107Sandi * @param  string  $id     page ID
20815fae107Sandi * @param  string  $user   Username
20915fae107Sandi * @param  array   $groups Array of groups the user is in
21015fae107Sandi * @return int             permission level
211f3f0262cSandi */
212f3f0262cSandifunction auth_aclcheck($id,$user,$groups){
213f3f0262cSandi  global $conf;
214f3f0262cSandi  global $AUTH_ACL;
215f3f0262cSandi
216f3f0262cSandi  # if no ACL is used always return upload rights
217f3f0262cSandi  if(!$conf['useacl']) return AUTH_UPLOAD;
218f3f0262cSandi
21910a76f6fSfrank  //if user is superuser return 255 (acl_admin)
22010a76f6fSfrank  if($conf['superuser'] == $user) { return AUTH_ADMIN; }
22110a76f6fSfrank
222074cf26bSandi  //make sure groups is an array
223074cf26bSandi  if(!is_array($groups)) $groups = array();
224074cf26bSandi
22510a76f6fSfrank  //prepend groups with @
2262cd2db38Sandi  $cnt = count($groups);
2272cd2db38Sandi  for($i=0; $i<$cnt; $i++){
22810a76f6fSfrank    $groups[$i] = '@'.$groups[$i];
22910a76f6fSfrank  }
23010a76f6fSfrank  //if user is in superuser group return 255 (acl_admin)
23110a76f6fSfrank  if(in_array($conf['superuser'], $groups)) { return AUTH_ADMIN; }
23210a76f6fSfrank
233f3f0262cSandi  $ns    = getNS($id);
234f3f0262cSandi  $perm  = -1;
235f3f0262cSandi
236f3f0262cSandi  if($user){
237f3f0262cSandi    //add ALL group
238f3f0262cSandi    $groups[] = '@ALL';
239f3f0262cSandi    //add User
240f3f0262cSandi    $groups[] = $user;
241f3f0262cSandi    //build regexp
242f3f0262cSandi    $regexp   = join('|',$groups);
243f3f0262cSandi  }else{
244f3f0262cSandi    $regexp = '@ALL';
245f3f0262cSandi  }
246f3f0262cSandi
247f3f0262cSandi  //check exact match first
248f3f0262cSandi  $matches = preg_grep('/^'.$id.'\s+('.$regexp.')\s+/',$AUTH_ACL);
249f3f0262cSandi  if(count($matches)){
250f3f0262cSandi    foreach($matches as $match){
251f3f0262cSandi      $match = preg_replace('/#.*$/','',$match); //ignore comments
252f3f0262cSandi      $acl   = preg_split('/\s+/',$match);
2538ef6b7caSandi      if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
254f3f0262cSandi      if($acl[2] > $perm){
255f3f0262cSandi        $perm = $acl[2];
256f3f0262cSandi      }
257f3f0262cSandi    }
258f3f0262cSandi    if($perm > -1){
259f3f0262cSandi      //we had a match - return it
260f3f0262cSandi      return $perm;
261f3f0262cSandi    }
262f3f0262cSandi  }
263f3f0262cSandi
264f3f0262cSandi  //still here? do the namespace checks
265f3f0262cSandi  if($ns){
266f3f0262cSandi    $path = $ns.':\*';
267f3f0262cSandi  }else{
268f3f0262cSandi    $path = '\*'; //root document
269f3f0262cSandi  }
270f3f0262cSandi
271f3f0262cSandi  do{
272f3f0262cSandi    $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
273f3f0262cSandi    if(count($matches)){
274f3f0262cSandi      foreach($matches as $match){
275f3f0262cSandi        $match = preg_replace('/#.*$/','',$match); //ignore comments
276f3f0262cSandi        $acl   = preg_split('/\s+/',$match);
2778ef6b7caSandi        if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
278f3f0262cSandi        if($acl[2] > $perm){
279f3f0262cSandi          $perm = $acl[2];
280f3f0262cSandi        }
281f3f0262cSandi      }
282f3f0262cSandi      //we had a match - return it
283f3f0262cSandi      return $perm;
284f3f0262cSandi    }
285f3f0262cSandi
286f3f0262cSandi    //get next higher namespace
287f3f0262cSandi    $ns   = getNS($ns);
288f3f0262cSandi
289f3f0262cSandi    if($path != '\*'){
290f3f0262cSandi      $path = $ns.':\*';
291f3f0262cSandi      if($path == ':\*') $path = '\*';
292f3f0262cSandi    }else{
293f3f0262cSandi      //we did this already
294f3f0262cSandi      //looks like there is something wrong with the ACL
295f3f0262cSandi      //break here
296f3f0262cSandi      return $perm;
297f3f0262cSandi    }
298f3f0262cSandi  }while(1); //this should never loop endless
29952a5af8dSandi
30052a5af8dSandi  //still here? return no permissions
30152a5af8dSandi  return AUTH_NONE;
302f3f0262cSandi}
303f3f0262cSandi
304f3f0262cSandi/**
305f3f0262cSandi * Create a pronouncable password
306f3f0262cSandi *
30715fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
30815fae107Sandi * @link    http://www.phpbuilder.com/annotate/message.php3?id=1014451
30915fae107Sandi *
31015fae107Sandi * @return string  pronouncable password
311f3f0262cSandi */
312f3f0262cSandifunction auth_pwgen(){
313f3f0262cSandi  $pw = '';
314f3f0262cSandi  $c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
315f3f0262cSandi  $v  = 'aeiou';              //vowels
316f3f0262cSandi  $a  = $c.$v;                //both
317f3f0262cSandi
318f3f0262cSandi  //use two syllables...
319f3f0262cSandi  for($i=0;$i < 2; $i++){
320f3f0262cSandi    $pw .= $c[rand(0, strlen($c)-1)];
321f3f0262cSandi    $pw .= $v[rand(0, strlen($v)-1)];
322f3f0262cSandi    $pw .= $a[rand(0, strlen($a)-1)];
323f3f0262cSandi  }
324f3f0262cSandi  //... and add a nice number
325f3f0262cSandi  $pw .= rand(10,99);
326f3f0262cSandi
327f3f0262cSandi  return $pw;
328f3f0262cSandi}
329f3f0262cSandi
330f3f0262cSandi/**
331f3f0262cSandi * Sends a password to the given user
332f3f0262cSandi *
33315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
33415fae107Sandi *
33515fae107Sandi * @return bool  true on success
336f3f0262cSandi */
337f3f0262cSandifunction auth_sendPassword($user,$password){
338f3f0262cSandi  global $conf;
339f3f0262cSandi  global $lang;
340f3f0262cSandi  $hdrs  = '';
34187ddda95Sandi  $userinfo = auth_getUserData($user);
342f3f0262cSandi
34387ddda95Sandi  if(!$userinfo['mail']) return false;
344f3f0262cSandi
345f3f0262cSandi  $text = rawLocale('password');
346ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
34787ddda95Sandi  $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
348f3f0262cSandi  $text = str_replace('@LOGIN@',$user,$text);
349f3f0262cSandi  $text = str_replace('@PASSWORD@',$password,$text);
350f3f0262cSandi  $text = str_replace('@TITLE@',$conf['title'],$text);
351f3f0262cSandi
35244f669e9Sandi  return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
35344f669e9Sandi                   $lang['regpwmail'],
35444f669e9Sandi                   $text,
35544f669e9Sandi                   $conf['mailfrom']);
356f3f0262cSandi}
357f3f0262cSandi
358f3f0262cSandi/**
35915fae107Sandi * Register a new user
360f3f0262cSandi *
36115fae107Sandi * This registers a new user - Data is read directly from $_POST
36215fae107Sandi *
36315fae107Sandi * @author  Andreas Gohr <andi@splitbrain.org>
36415fae107Sandi *
36515fae107Sandi * @return bool  true on success, false on any error
366f3f0262cSandi */
367f3f0262cSandifunction register(){
368f3f0262cSandi  global $lang;
369eb5d07e4Sjan  global $conf;
370f3f0262cSandi
371f3f0262cSandi  if(!$_POST['save']) return false;
372640145a5Sandi
373f3f0262cSandi  //clean username
374f3f0262cSandi  $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
375f3f0262cSandi  $_POST['login'] = cleanID($_POST['login']);
376f3f0262cSandi  //clean fullname and email
377f3f0262cSandi  $_POST['fullname'] = trim(str_replace(':','',$_POST['fullname']));
378f3f0262cSandi  $_POST['email']    = trim(str_replace(':','',$_POST['email']));
379f3f0262cSandi
380f3f0262cSandi  if( empty($_POST['login']) ||
381f3f0262cSandi      empty($_POST['fullname']) ||
382f3f0262cSandi      empty($_POST['email']) ){
383f3f0262cSandi    msg($lang['regmissing'],-1);
384f3f0262cSandi    return false;
385f3f0262cSandi  }
386f3f0262cSandi
387cab2716aSmatthias.grimm  if ($conf['autopasswd']) {
388cab2716aSmatthias.grimm    $pass = auth_pwgen();                // automatically generate password
389cab2716aSmatthias.grimm  } elseif (empty($_POST['pass']) ||
390cab2716aSmatthias.grimm            empty($_POST['passchk'])) {
391bf12ec81Sjan    msg($lang['regmissing'], -1);        // complain about missing passwords
392cab2716aSmatthias.grimm    return false;
393cab2716aSmatthias.grimm  } elseif ($_POST['pass'] != $_POST['passchk']) {
394bf12ec81Sjan    msg($lang['regbadpass'], -1);      // complain about misspelled passwords
395cab2716aSmatthias.grimm    return false;
396cab2716aSmatthias.grimm  } else {
397cab2716aSmatthias.grimm    $pass = $_POST['pass'];              // accept checked and valid password
398cab2716aSmatthias.grimm  }
399cab2716aSmatthias.grimm
400f3f0262cSandi  //check mail
40144f669e9Sandi  if(!mail_isvalid($_POST['email'])){
402f3f0262cSandi    msg($lang['regbadmail'],-1);
403f3f0262cSandi    return false;
404f3f0262cSandi  }
405f3f0262cSandi
406f3f0262cSandi  //okay try to create the user
4077c37db8aSmatthias.grimm  $pass = auth_createUser($_POST['login'],$pass,$_POST['fullname'],$_POST['email']);
408f3f0262cSandi  if(empty($pass)){
409f3f0262cSandi    msg($lang['reguexists'],-1);
410f3f0262cSandi    return false;
411f3f0262cSandi  }
412f3f0262cSandi
413cab2716aSmatthias.grimm  if (!$conf['autopasswd']) {
414cab2716aSmatthias.grimm    msg($lang['regsuccess2'],1);
415cab2716aSmatthias.grimm    return true;
416cab2716aSmatthias.grimm  }
417cab2716aSmatthias.grimm
418cab2716aSmatthias.grimm  // autogenerated password? then send him the password
419f3f0262cSandi  if (auth_sendPassword($_POST['login'],$pass)){
420f3f0262cSandi    msg($lang['regsuccess'],1);
421f3f0262cSandi    return true;
422f3f0262cSandi  }else{
423f3f0262cSandi    msg($lang['regmailfail'],-1);
424f3f0262cSandi    return false;
425f3f0262cSandi  }
426f3f0262cSandi}
427f3f0262cSandi
42810a76f6fSfrank/**
42910a76f6fSfrank * Uses a regular expresion to check if a given mail address is valid
43010a76f6fSfrank *
43110a76f6fSfrank * May not be completly RFC conform!
43210a76f6fSfrank *
43310a76f6fSfrank * @link    http://www.webmasterworld.com/forum88/135.htm
43410a76f6fSfrank *
43510a76f6fSfrank * @param   string $email the address to check
43610a76f6fSfrank * @return  bool          true if address is valid
43710a76f6fSfrank */
43810a76f6fSfrankfunction isvalidemail($email){
43910a76f6fSfrank  return eregi("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,4}$", $email);
44010a76f6fSfrank}
44110a76f6fSfrank
442b0855b11Sandi/**
443b0855b11Sandi * Encrypts a password using the given method and salt
444b0855b11Sandi *
445b0855b11Sandi * If the selected method needs a salt and none was given, a random one
446b0855b11Sandi * is chosen.
447b0855b11Sandi *
448b0855b11Sandi * The following methods are understood:
449b0855b11Sandi *
450b0855b11Sandi *   smd5  - Salted MD5 hashing
451b0855b11Sandi *   md5   - Simple MD5 hashing
452b0855b11Sandi *   sha1  - SHA1 hashing
453b0855b11Sandi *   ssha  - Salted SHA1 hashing
454d7be6245Sandi *   crypt - Unix crypt
455d7be6245Sandi *   mysql - MySQL password (old method)
456d7be6245Sandi *   my411 - MySQL 4.1.1 password
457b0855b11Sandi *
458b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
459b0855b11Sandi * @return  string  The crypted password
460b0855b11Sandi */
461b0855b11Sandifunction auth_cryptPassword($clear,$method='',$salt=''){
462b0855b11Sandi  global $conf;
463b0855b11Sandi  if(empty($method)) $method = $conf['passcrypt'];
46410a76f6fSfrank
465b0855b11Sandi  //prepare a salt
466b0855b11Sandi  if(empty($salt)) $salt = md5(uniqid(rand(), true));
467b0855b11Sandi
468b0855b11Sandi  switch(strtolower($method)){
469b0855b11Sandi    case 'smd5':
470b0855b11Sandi        return crypt($clear,'$1$'.substr($salt,0,8).'$');
471b0855b11Sandi    case 'md5':
472b0855b11Sandi      return md5($clear);
473b0855b11Sandi    case 'sha1':
474b0855b11Sandi      return sha1($clear);
475b0855b11Sandi    case 'ssha':
476b0855b11Sandi      $salt=substr($salt,0,4);
477d6e54e02Smatthiasgrimm      return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
478b0855b11Sandi    case 'crypt':
479b0855b11Sandi      return crypt($clear,substr($salt,0,2));
480d7be6245Sandi    case 'mysql':
481d7be6245Sandi      //from http://www.php.net/mysql comment by <soren at byu dot edu>
482d7be6245Sandi      $nr=0x50305735;
483d7be6245Sandi      $nr2=0x12345671;
484d7be6245Sandi      $add=7;
485d7be6245Sandi      $charArr = preg_split("//", $clear);
486d7be6245Sandi      foreach ($charArr as $char) {
487d7be6245Sandi        if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
488d7be6245Sandi        $charVal = ord($char);
489d7be6245Sandi        $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
490d7be6245Sandi        $nr2 += ($nr2 << 8) ^ $nr;
491d7be6245Sandi        $add += $charVal;
492d7be6245Sandi      }
493d7be6245Sandi      return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
494d7be6245Sandi    case 'my411':
495d7be6245Sandi      return '*'.sha1(pack("H*", sha1($clear)));
496b0855b11Sandi    default:
497b0855b11Sandi      msg("Unsupported crypt method $method",-1);
498b0855b11Sandi  }
499b0855b11Sandi}
500b0855b11Sandi
501b0855b11Sandi/**
502b0855b11Sandi * Verifies a cleartext password against a crypted hash
503b0855b11Sandi *
504b0855b11Sandi * The method and salt used for the crypted hash is determined automatically
505b0855b11Sandi * then the clear text password is crypted using the same method. If both hashs
506b0855b11Sandi * match true is is returned else false
507b0855b11Sandi *
508b0855b11Sandi * @author  Andreas Gohr <andi@splitbrain.org>
509b0855b11Sandi * @return  bool
510b0855b11Sandi */
511b0855b11Sandifunction auth_verifyPassword($clear,$crypt){
512b0855b11Sandi  $method='';
513b0855b11Sandi  $salt='';
514b0855b11Sandi
515b0855b11Sandi  //determine the used method and salt
516d7be6245Sandi  $len = strlen($crypt);
517b0855b11Sandi  if(substr($crypt,0,3) == '$1$'){
518b0855b11Sandi    $method = 'smd5';
519b0855b11Sandi    $salt   = substr($crypt,3,8);
520b0855b11Sandi  }elseif(substr($crypt,0,6) == '{SSHA}'){
521b0855b11Sandi    $method = 'ssha';
522b0855b11Sandi    $salt   = substr(base64_decode(substr($crypt, 6)),20);
523d7be6245Sandi  }elseif($len == 32){
524b0855b11Sandi    $method = 'md5';
525d7be6245Sandi  }elseif($len == 40){
526b0855b11Sandi    $method = 'sha1';
527d7be6245Sandi  }elseif($len == 16){
528d7be6245Sandi    $method = 'mysql';
529d7be6245Sandi  }elseif($len == 41 && $crypt[0] == '*'){
530d7be6245Sandi    $method = 'my411';
531b0855b11Sandi  }else{
532b0855b11Sandi    $method = 'crypt';
533b0855b11Sandi    $salt   = substr($crypt,0,2);
534b0855b11Sandi  }
535b0855b11Sandi
536b0855b11Sandi  //crypt and compare
537b0855b11Sandi  if(auth_cryptPassword($clear,$method,$salt) === $crypt){
538b0855b11Sandi    return true;
539b0855b11Sandi  }
540b0855b11Sandi  return false;
541b0855b11Sandi}
542340756e4Sandi
543340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
544