Added group and user sanitation
[dokuwiki.git] / inc / auth.php
blob6157ac8927c77e182e04e1a3791080ea182c0206
1 <?php
2 /**
3 * Authentication library
5 * Including this file will automatically try to login
6 * a user by calling auth_login()
8 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author Andreas Gohr <andi@splitbrain.org>
12 if(!defined('DOKU_INC')) die('meh.');
13 require_once(DOKU_INC.'inc/common.php');
14 require_once(DOKU_INC.'inc/io.php');
16 // some ACL level defines
17 define('AUTH_NONE',0);
18 define('AUTH_READ',1);
19 define('AUTH_EDIT',2);
20 define('AUTH_CREATE',4);
21 define('AUTH_UPLOAD',8);
22 define('AUTH_DELETE',16);
23 define('AUTH_ADMIN',255);
25 global $conf;
27 if($conf['useacl']){
28 require_once(DOKU_INC.'inc/blowfish.php');
29 require_once(DOKU_INC.'inc/mail.php');
31 global $auth;
33 // load the the backend auth functions and instantiate the auth object
34 if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
35 require_once(DOKU_INC.'inc/auth/basic.class.php');
36 require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
38 $auth_class = "auth_".$conf['authtype'];
39 if (class_exists($auth_class)) {
40 $auth = new $auth_class();
41 if ($auth->success == false) {
42 // degrade to unauthenticated user
43 unset($auth);
44 auth_logoff();
45 msg($lang['authtempfail'], -1);
47 } else {
48 nice_die($lang['authmodfailed']);
50 } else {
51 nice_die($lang['authmodfailed']);
55 // do the login either by cookie or provided credentials
56 if($conf['useacl']){
57 if($auth){
58 if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
59 if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
60 if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
61 $_REQUEST['http_credentials'] = false;
62 if (!$conf['rememberme']) $_REQUEST['r'] = false;
64 // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
65 if(isset($_SERVER['HTTP_AUTHORIZATION'])){
66 list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
67 explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
70 // if no credentials were given try to use HTTP auth (for SSO)
71 if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
72 $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
73 $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
74 $_REQUEST['http_credentials'] = true;
77 // apply cleaning
78 $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
80 if(isset($_REQUEST['authtok'])){
81 // when an authentication token is given, trust the session
82 auth_validateToken($_REQUEST['authtok']);
83 }elseif(!is_null($auth) && $auth->canDo('external')){
84 // external trust mechanism in place
85 $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
86 }else{
87 $evdata = array(
88 'user' => $_REQUEST['u'],
89 'password' => $_REQUEST['p'],
90 'sticky' => $_REQUEST['r'],
91 'silent' => $_REQUEST['http_credentials'],
93 $evt = new Doku_Event('AUTH_LOGIN_CHECK',$evdata);
94 if($evt->advise_before()){
95 auth_login($evdata['user'],
96 $evdata['password'],
97 $evdata['sticky'],
98 $evdata['silent']);
103 //load ACL into a global array
104 global $AUTH_ACL;
105 if(is_readable(DOKU_CONF.'acl.auth.php')){
106 $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
107 //support user wildcard
108 if(isset($_SERVER['REMOTE_USER'])){
109 $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
110 $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); //legacy
112 }else{
113 $AUTH_ACL = array();
118 * This tries to login the user based on the sent auth credentials
120 * The authentication works like this: if a username was given
121 * a new login is assumed and user/password are checked. If they
122 * are correct the password is encrypted with blowfish and stored
123 * together with the username in a cookie - the same info is stored
124 * in the session, too. Additonally a browserID is stored in the
125 * session.
127 * If no username was given the cookie is checked: if the username,
128 * crypted password and browserID match between session and cookie
129 * no further testing is done and the user is accepted
131 * If a cookie was found but no session info was availabe the
132 * blowfish encrypted password from the cookie is decrypted and
133 * together with username rechecked by calling this function again.
135 * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
136 * are set.
138 * @author Andreas Gohr <andi@splitbrain.org>
140 * @param string $user Username
141 * @param string $pass Cleartext Password
142 * @param bool $sticky Cookie should not expire
143 * @param bool $silent Don't show error on bad auth
144 * @return bool true on successful auth
146 function auth_login($user,$pass,$sticky=false,$silent=false){
147 global $USERINFO;
148 global $conf;
149 global $lang;
150 global $auth;
151 $sticky ? $sticky = true : $sticky = false; //sanity check
153 if(!empty($user)){
154 //usual login
155 if ($auth->checkPass($user,$pass)){
156 // make logininfo globally available
157 $_SERVER['REMOTE_USER'] = $user;
158 auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
159 return true;
160 }else{
161 //invalid credentials - log off
162 if(!$silent) msg($lang['badlogin'],-1);
163 auth_logoff();
164 return false;
166 }else{
167 // read cookie information
168 list($user,$sticky,$pass) = auth_getCookie();
169 // get session info
170 $session = $_SESSION[DOKU_COOKIE]['auth'];
171 if($user && $pass){
172 // we got a cookie - see if we can trust it
173 if(isset($session) &&
174 $auth->useSessionCache($user) &&
175 ($session['time'] >= time()-$conf['auth_security_timeout']) &&
176 ($session['user'] == $user) &&
177 ($session['pass'] == $pass) && //still crypted
178 ($session['buid'] == auth_browseruid()) ){
179 // he has session, cookie and browser right - let him in
180 $_SERVER['REMOTE_USER'] = $user;
181 $USERINFO = $session['info']; //FIXME move all references to session
182 return true;
184 // no we don't trust it yet - recheck pass but silent
185 $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
186 return auth_login($user,$pass,$sticky,true);
189 //just to be sure
190 auth_logoff(true);
191 return false;
195 * Checks if a given authentication token was stored in the session
197 * Will setup authentication data using data from the session if the
198 * token is correct. Will exit with a 401 Status if not.
200 * @author Andreas Gohr <andi@splitbrain.org>
201 * @param string $token The authentication token
202 * @return boolean true (or will exit on failure)
204 function auth_validateToken($token){
205 if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
206 // bad token
207 header("HTTP/1.0 401 Unauthorized");
208 print 'Invalid auth token - maybe the session timed out';
209 unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
210 exit;
212 // still here? trust the session data
213 global $USERINFO;
214 $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
215 $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
216 return true;
220 * Create an auth token and store it in the session
222 * NOTE: this is completely unrelated to the getSecurityToken() function
224 * @author Andreas Gohr <andi@splitbrain.org>
225 * @return string The auth token
227 function auth_createToken(){
228 $token = md5(mt_rand());
229 @session_start(); // reopen the session if needed
230 $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
231 session_write_close();
232 return $token;
236 * Builds a pseudo UID from browser and IP data
238 * This is neither unique nor unfakable - still it adds some
239 * security. Using the first part of the IP makes sure
240 * proxy farms like AOLs are stil okay.
242 * @author Andreas Gohr <andi@splitbrain.org>
244 * @return string a MD5 sum of various browser headers
246 function auth_browseruid(){
247 $ip = clientIP(true);
248 $uid = '';
249 $uid .= $_SERVER['HTTP_USER_AGENT'];
250 $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
251 $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
252 $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
253 $uid .= substr($ip,0,strpos($ip,'.'));
254 return md5($uid);
258 * Creates a random key to encrypt the password in cookies
260 * This function tries to read the password for encrypting
261 * cookies from $conf['metadir'].'/_htcookiesalt'
262 * if no such file is found a random key is created and
263 * and stored in this file.
265 * @author Andreas Gohr <andi@splitbrain.org>
267 * @return string
269 function auth_cookiesalt(){
270 global $conf;
271 $file = $conf['metadir'].'/_htcookiesalt';
272 $salt = io_readFile($file);
273 if(empty($salt)){
274 $salt = uniqid(rand(),true);
275 io_saveFile($file,$salt);
277 return $salt;
281 * Log out the current user
283 * This clears all authentication data and thus log the user
284 * off. It also clears session data.
286 * @author Andreas Gohr <andi@splitbrain.org>
287 * @param bool $keepbc - when true, the breadcrumb data is not cleared
289 function auth_logoff($keepbc=false){
290 global $conf;
291 global $USERINFO;
292 global $INFO, $ID;
293 global $auth;
295 // make sure the session is writable (it usually is)
296 @session_start();
298 if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
299 unset($_SESSION[DOKU_COOKIE]['auth']['user']);
300 if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
301 unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
302 if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
303 unset($_SESSION[DOKU_COOKIE]['auth']['info']);
304 if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
305 unset($_SESSION[DOKU_COOKIE]['bc']);
306 if(isset($_SERVER['REMOTE_USER']))
307 unset($_SERVER['REMOTE_USER']);
308 $USERINFO=null; //FIXME
310 if (version_compare(PHP_VERSION, '5.2.0', '>')) {
311 setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
312 }else{
313 setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
316 if($auth && $auth->canDo('logoff')){
317 $auth->logOff();
322 * Check if a user is a manager
324 * Should usually be called without any parameters to check the current
325 * user.
327 * The info is available through $INFO['ismanager'], too
329 * @author Andreas Gohr <andi@splitbrain.org>
330 * @see auth_isadmin
331 * @param string user - Username
332 * @param array groups - List of groups the user is in
333 * @param bool adminonly - when true checks if user is admin
335 function auth_ismanager($user=null,$groups=null,$adminonly=false){
336 global $conf;
337 global $USERINFO;
339 if(!$conf['useacl']) return false;
340 if(is_null($user)) {
341 if (!isset($_SERVER['REMOTE_USER'])) {
342 return false;
343 } else {
344 $user = $_SERVER['REMOTE_USER'];
347 if(is_null($groups)) $groups = (array) $USERINFO['grps'];
348 $user = auth_nameencode($user);
350 // check username against superuser and manager
351 $superusers = explode(',', $conf['superuser']);
352 $superusers = array_unique($superusers);
353 $superusers = array_map('trim', $superusers);
354 // prepare an array containing only true values for array_map call
355 $alltrue = array_fill(0, count($superusers), true);
356 $superusers = array_map('auth_nameencode', $superusers, $alltrue);
357 if(in_array($user, $superusers)) return true;
359 if(!$adminonly){
360 $managers = explode(',', $conf['manager']);
361 $managers = array_unique($managers);
362 $managers = array_map('trim', $managers);
363 // prepare an array containing only true values for array_map call
364 $alltrue = array_fill(0, count($managers), true);
365 $managers = array_map('auth_nameencode', $managers, $alltrue);
366 if(in_array($user, $managers)) return true;
369 // check user's groups against superuser and manager
370 if (!empty($groups)) {
372 //prepend groups with @ and nameencode
373 $cnt = count($groups);
374 for($i=0; $i<$cnt; $i++){
375 $groups[$i] = '@'.auth_nameencode($groups[$i]);
378 // check groups against superuser and manager
379 foreach($superusers as $supu)
380 if(in_array($supu, $groups)) return true;
381 if(!$adminonly){
382 foreach($managers as $mana)
383 if(in_array($mana, $groups)) return true;
387 return false;
391 * Check if a user is admin
393 * Alias to auth_ismanager with adminonly=true
395 * The info is available through $INFO['isadmin'], too
397 * @author Andreas Gohr <andi@splitbrain.org>
398 * @see auth_ismanager
400 function auth_isadmin($user=null,$groups=null){
401 return auth_ismanager($user,$groups,true);
405 * Convinience function for auth_aclcheck()
407 * This checks the permissions for the current user
409 * @author Andreas Gohr <andi@splitbrain.org>
411 * @param string $id page ID (needs to be resolved and cleaned)
412 * @return int permission level
414 function auth_quickaclcheck($id){
415 global $conf;
416 global $USERINFO;
417 # if no ACL is used always return upload rights
418 if(!$conf['useacl']) return AUTH_UPLOAD;
419 return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
423 * Returns the maximum rights a user has for
424 * the given ID or its namespace
426 * @author Andreas Gohr <andi@splitbrain.org>
428 * @param string $id page ID (needs to be resolved and cleaned)
429 * @param string $user Username
430 * @param array $groups Array of groups the user is in
431 * @return int permission level
433 function auth_aclcheck($id,$user,$groups){
434 global $conf;
435 global $AUTH_ACL;
437 // if no ACL is used always return upload rights
438 if(!$conf['useacl']) return AUTH_UPLOAD;
440 //make sure groups is an array
441 if(!is_array($groups)) $groups = array();
443 //if user is superuser or in superusergroup return 255 (acl_admin)
444 if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
446 $user = auth_nameencode($user);
448 //prepend groups with @ and nameencode
449 $cnt = count($groups);
450 for($i=0; $i<$cnt; $i++){
451 $groups[$i] = '@'.auth_nameencode($groups[$i]);
454 $ns = getNS($id);
455 $perm = -1;
457 if($user || count($groups)){
458 //add ALL group
459 $groups[] = '@ALL';
460 //add User
461 if($user) $groups[] = $user;
462 //build regexp
463 $regexp = join('|',$groups);
464 }else{
465 $regexp = '@ALL';
468 //check exact match first
469 $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/',$AUTH_ACL);
470 if(count($matches)){
471 foreach($matches as $match){
472 $match = preg_replace('/#.*$/','',$match); //ignore comments
473 $acl = preg_split('/\s+/',$match);
474 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
475 if($acl[2] > $perm){
476 $perm = $acl[2];
479 if($perm > -1){
480 //we had a match - return it
481 return $perm;
485 //still here? do the namespace checks
486 if($ns){
487 $path = $ns.':\*';
488 }else{
489 $path = '\*'; //root document
493 $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/',$AUTH_ACL);
494 if(count($matches)){
495 foreach($matches as $match){
496 $match = preg_replace('/#.*$/','',$match); //ignore comments
497 $acl = preg_split('/\s+/',$match);
498 if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
499 if($acl[2] > $perm){
500 $perm = $acl[2];
503 //we had a match - return it
504 return $perm;
507 //get next higher namespace
508 $ns = getNS($ns);
510 if($path != '\*'){
511 $path = $ns.':\*';
512 if($path == ':\*') $path = '\*';
513 }else{
514 //we did this already
515 //looks like there is something wrong with the ACL
516 //break here
517 msg('No ACL setup yet! Denying access to everyone.');
518 return AUTH_NONE;
520 }while(1); //this should never loop endless
522 //still here? return no permissions
523 return AUTH_NONE;
527 * Encode ASCII special chars
529 * Some auth backends allow special chars in their user and groupnames
530 * The special chars are encoded with this function. Only ASCII chars
531 * are encoded UTF-8 multibyte are left as is (different from usual
532 * urlencoding!).
534 * Decoding can be done with rawurldecode
536 * @author Andreas Gohr <gohr@cosmocode.de>
537 * @see rawurldecode()
539 function auth_nameencode($name,$skip_group=false){
540 global $cache_authname;
541 $cache =& $cache_authname;
542 $name = (string) $name;
544 if (!isset($cache[$name][$skip_group])) {
545 if($skip_group && $name{0} =='@'){
546 $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
547 "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
548 }else{
549 $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
550 "'%'.dechex(ord(substr('\\1',-1)))",$name);
554 return $cache[$name][$skip_group];
558 * Create a pronouncable password
560 * @author Andreas Gohr <andi@splitbrain.org>
561 * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
563 * @return string pronouncable password
565 function auth_pwgen(){
566 $pw = '';
567 $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
568 $v = 'aeiou'; //vowels
569 $a = $c.$v; //both
571 //use two syllables...
572 for($i=0;$i < 2; $i++){
573 $pw .= $c[rand(0, strlen($c)-1)];
574 $pw .= $v[rand(0, strlen($v)-1)];
575 $pw .= $a[rand(0, strlen($a)-1)];
577 //... and add a nice number
578 $pw .= rand(10,99);
580 return $pw;
584 * Sends a password to the given user
586 * @author Andreas Gohr <andi@splitbrain.org>
588 * @return bool true on success
590 function auth_sendPassword($user,$password){
591 global $conf;
592 global $lang;
593 global $auth;
595 $hdrs = '';
596 $userinfo = $auth->getUserData($user);
598 if(!$userinfo['mail']) return false;
600 $text = rawLocale('password');
601 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
602 $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
603 $text = str_replace('@LOGIN@',$user,$text);
604 $text = str_replace('@PASSWORD@',$password,$text);
605 $text = str_replace('@TITLE@',$conf['title'],$text);
607 return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
608 $lang['regpwmail'],
609 $text,
610 $conf['mailfrom']);
614 * Register a new user
616 * This registers a new user - Data is read directly from $_POST
618 * @author Andreas Gohr <andi@splitbrain.org>
620 * @return bool true on success, false on any error
622 function register(){
623 global $lang;
624 global $conf;
625 global $auth;
627 if(!$_POST['save']) return false;
628 if(!$auth->canDo('addUser')) return false;
630 //clean username
631 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
632 $_POST['login'] = cleanID($_POST['login']);
633 //clean fullname and email
634 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
635 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
637 if( empty($_POST['login']) ||
638 empty($_POST['fullname']) ||
639 empty($_POST['email']) ){
640 msg($lang['regmissing'],-1);
641 return false;
644 if ($conf['autopasswd']) {
645 $pass = auth_pwgen(); // automatically generate password
646 } elseif (empty($_POST['pass']) ||
647 empty($_POST['passchk'])) {
648 msg($lang['regmissing'], -1); // complain about missing passwords
649 return false;
650 } elseif ($_POST['pass'] != $_POST['passchk']) {
651 msg($lang['regbadpass'], -1); // complain about misspelled passwords
652 return false;
653 } else {
654 $pass = $_POST['pass']; // accept checked and valid password
657 //check mail
658 if(!mail_isvalid($_POST['email'])){
659 msg($lang['regbadmail'],-1);
660 return false;
663 //okay try to create the user
664 if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
665 msg($lang['reguexists'],-1);
666 return false;
669 // create substitutions for use in notification email
670 $substitutions = array(
671 'NEWUSER' => $_POST['login'],
672 'NEWNAME' => $_POST['fullname'],
673 'NEWEMAIL' => $_POST['email'],
676 if (!$conf['autopasswd']) {
677 msg($lang['regsuccess2'],1);
678 notify('', 'register', '', $_POST['login'], false, $substitutions);
679 return true;
682 // autogenerated password? then send him the password
683 if (auth_sendPassword($_POST['login'],$pass)){
684 msg($lang['regsuccess'],1);
685 notify('', 'register', '', $_POST['login'], false, $substitutions);
686 return true;
687 }else{
688 msg($lang['regmailfail'],-1);
689 return false;
694 * Update user profile
696 * @author Christopher Smith <chris@jalakai.co.uk>
698 function updateprofile() {
699 global $conf;
700 global $INFO;
701 global $lang;
702 global $auth;
704 if(empty($_POST['save'])) return false;
705 if(!checkSecurityToken()) return false;
707 // should not be able to get here without Profile being possible...
708 if(!$auth->canDo('Profile')) {
709 msg($lang['profna'],-1);
710 return false;
713 if ($_POST['newpass'] != $_POST['passchk']) {
714 msg($lang['regbadpass'], -1); // complain about misspelled passwords
715 return false;
718 //clean fullname and email
719 $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
720 $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
722 if (empty($_POST['fullname']) || empty($_POST['email'])) {
723 msg($lang['profnoempty'],-1);
724 return false;
727 if (!mail_isvalid($_POST['email'])){
728 msg($lang['regbadmail'],-1);
729 return false;
732 if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
733 if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
734 if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
736 if (!count($changes)) {
737 msg($lang['profnochange'], -1);
738 return false;
741 if ($conf['profileconfirm']) {
742 if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
743 msg($lang['badlogin'],-1);
744 return false;
748 if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
749 // update cookie and session with the changed data
750 $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
751 list($user,$sticky,$pass) = explode('|',$cookie,3);
752 if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
754 auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
755 return true;
760 * Send a new password
762 * This function handles both phases of the password reset:
764 * - handling the first request of password reset
765 * - validating the password reset auth token
767 * @author Benoit Chesneau <benoit@bchesneau.info>
768 * @author Chris Smith <chris@jalakai.co.uk>
769 * @author Andreas Gohr <andi@splitbrain.org>
771 * @return bool true on success, false on any error
773 function act_resendpwd(){
774 global $lang;
775 global $conf;
776 global $auth;
778 if(!actionOK('resendpwd')) return false;
780 // should not be able to get here without modPass being possible...
781 if(!$auth->canDo('modPass')) {
782 msg($lang['resendna'],-1);
783 return false;
786 $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
788 if($token){
789 // we're in token phase
791 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
792 if(!@file_exists($tfile)){
793 msg($lang['resendpwdbadauth'],-1);
794 return false;
796 $user = io_readfile($tfile);
797 @unlink($tfile);
798 $userinfo = $auth->getUserData($user);
799 if(!$userinfo['mail']) {
800 msg($lang['resendpwdnouser'], -1);
801 return false;
804 $pass = auth_pwgen();
805 if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
806 msg('error modifying user data',-1);
807 return false;
810 if (auth_sendPassword($user,$pass)) {
811 msg($lang['resendpwdsuccess'],1);
812 } else {
813 msg($lang['regmailfail'],-1);
815 return true;
817 } else {
818 // we're in request phase
820 if(!$_POST['save']) return false;
822 if (empty($_POST['login'])) {
823 msg($lang['resendpwdmissing'], -1);
824 return false;
825 } else {
826 $_POST['login'] = preg_replace('/.*:/','',$_POST['login']);
827 $user = cleanID($_POST['login']);
830 $userinfo = $auth->getUserData($user);
831 if(!$userinfo['mail']) {
832 msg($lang['resendpwdnouser'], -1);
833 return false;
836 // generate auth token
837 $token = md5(auth_cookiesalt().$user); //secret but user based
838 $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
839 $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
841 io_saveFile($tfile,$user);
843 $text = rawLocale('pwconfirm');
844 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
845 $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
846 $text = str_replace('@LOGIN@',$user,$text);
847 $text = str_replace('@TITLE@',$conf['title'],$text);
848 $text = str_replace('@CONFIRM@',$url,$text);
850 if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
851 $lang['regpwmail'],
852 $text,
853 $conf['mailfrom'])){
854 msg($lang['resendpwdconfirm'],1);
855 }else{
856 msg($lang['regmailfail'],-1);
858 return true;
861 return false; // never reached
865 * Encrypts a password using the given method and salt
867 * If the selected method needs a salt and none was given, a random one
868 * is chosen.
870 * The following methods are understood:
872 * smd5 - Salted MD5 hashing
873 * apr1 - Apache salted MD5 hashing
874 * md5 - Simple MD5 hashing
875 * sha1 - SHA1 hashing
876 * ssha - Salted SHA1 hashing
877 * crypt - Unix crypt
878 * mysql - MySQL password (old method)
879 * my411 - MySQL 4.1.1 password
880 * kmd5 - Salted MD5 hashing as used by UNB
882 * @author Andreas Gohr <andi@splitbrain.org>
883 * @return string The crypted password
885 function auth_cryptPassword($clear,$method='',$salt=null){
886 global $conf;
887 if(empty($method)) $method = $conf['passcrypt'];
889 //prepare a salt
890 if(is_null($salt)) $salt = md5(uniqid(rand(), true));
892 switch(strtolower($method)){
893 case 'smd5':
894 if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
895 // when crypt can't handle SMD5, falls through to pure PHP implementation
896 $magic = '1';
897 case 'apr1':
898 //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
899 if(!$magic) $magic = 'apr1';
900 $salt = substr($salt,0,8);
901 $len = strlen($clear);
902 $text = $clear.'$'.$magic.'$'.$salt;
903 $bin = pack("H32", md5($clear.$salt.$clear));
904 for($i = $len; $i > 0; $i -= 16) {
905 $text .= substr($bin, 0, min(16, $i));
907 for($i = $len; $i > 0; $i >>= 1) {
908 $text .= ($i & 1) ? chr(0) : $clear{0};
910 $bin = pack("H32", md5($text));
911 for($i = 0; $i < 1000; $i++) {
912 $new = ($i & 1) ? $clear : $bin;
913 if ($i % 3) $new .= $salt;
914 if ($i % 7) $new .= $clear;
915 $new .= ($i & 1) ? $bin : $clear;
916 $bin = pack("H32", md5($new));
918 $tmp = '';
919 for ($i = 0; $i < 5; $i++) {
920 $k = $i + 6;
921 $j = $i + 12;
922 if ($j == 16) $j = 5;
923 $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
925 $tmp = chr(0).chr(0).$bin[11].$tmp;
926 $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
927 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
928 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
929 return '$'.$magic.'$'.$salt.'$'.$tmp;
930 case 'md5':
931 return md5($clear);
932 case 'sha1':
933 return sha1($clear);
934 case 'ssha':
935 $salt=substr($salt,0,4);
936 return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
937 case 'crypt':
938 return crypt($clear,substr($salt,0,2));
939 case 'mysql':
940 //from http://www.php.net/mysql comment by <soren at byu dot edu>
941 $nr=0x50305735;
942 $nr2=0x12345671;
943 $add=7;
944 $charArr = preg_split("//", $clear);
945 foreach ($charArr as $char) {
946 if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
947 $charVal = ord($char);
948 $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
949 $nr2 += ($nr2 << 8) ^ $nr;
950 $add += $charVal;
952 return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
953 case 'my411':
954 return '*'.sha1(pack("H*", sha1($clear)));
955 case 'kmd5':
956 $key = substr($salt, 16, 2);
957 $hash1 = strtolower(md5($key . md5($clear)));
958 $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
959 return $hash2;
960 default:
961 msg("Unsupported crypt method $method",-1);
966 * Verifies a cleartext password against a crypted hash
968 * The method and salt used for the crypted hash is determined automatically
969 * then the clear text password is crypted using the same method. If both hashs
970 * match true is is returned else false
972 * @author Andreas Gohr <andi@splitbrain.org>
973 * @return bool
975 function auth_verifyPassword($clear,$crypt){
976 $method='';
977 $salt='';
979 //determine the used method and salt
980 $len = strlen($crypt);
981 if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
982 $method = 'smd5';
983 $salt = $m[1];
984 }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
985 $method = 'apr1';
986 $salt = $m[1];
987 }elseif(substr($crypt,0,6) == '{SSHA}'){
988 $method = 'ssha';
989 $salt = substr(base64_decode(substr($crypt, 6)),20);
990 }elseif($len == 32){
991 $method = 'md5';
992 }elseif($len == 40){
993 $method = 'sha1';
994 }elseif($len == 16){
995 $method = 'mysql';
996 }elseif($len == 41 && $crypt[0] == '*'){
997 $method = 'my411';
998 }elseif($len == 34){
999 $method = 'kmd5';
1000 $salt = $crypt;
1001 }else{
1002 $method = 'crypt';
1003 $salt = substr($crypt,0,2);
1006 //crypt and compare
1007 if(auth_cryptPassword($clear,$method,$salt) === $crypt){
1008 return true;
1010 return false;
1014 * Set the authentication cookie and add user identification data to the session
1016 * @param string $user username
1017 * @param string $pass encrypted password
1018 * @param bool $sticky whether or not the cookie will last beyond the session
1020 function auth_setCookie($user,$pass,$sticky) {
1021 global $conf;
1022 global $auth;
1023 global $USERINFO;
1025 $USERINFO = $auth->getUserData($user);
1027 // set cookie
1028 $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
1029 $time = $sticky ? (time()+60*60*24*365) : 0; //one year
1030 if (version_compare(PHP_VERSION, '5.2.0', '>')) {
1031 setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
1032 }else{
1033 setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
1035 // set session
1036 $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
1037 $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
1038 $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
1039 $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
1040 $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
1044 * Returns the user, (encrypted) password and sticky bit from cookie
1046 * @returns array
1048 function auth_getCookie(){
1049 if (!isset($_COOKIE[DOKU_COOKIE])) {
1050 return array(null, null, null);
1052 list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
1053 $sticky = (bool) $sticky;
1054 $pass = base64_decode($pass);
1055 $user = base64_decode($user);
1056 return array($user,$sticky,$pass);
1059 //Setup VIM: ex: et ts=2 enc=utf-8 :