PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 2ms app.codeStats 0ms

/wiki/inc/auth.php

https://bitbucket.org/malathisuji/nrcfoss-au-tamil-computing-activities
PHP | 1090 lines | 671 code | 114 blank | 305 comment | 177 complexity | 15bbd48f18faf3e76849d798148c781a MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  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. if(!defined('DOKU_INC')) die('meh.');
  12. require_once(DOKU_INC.'inc/common.php');
  13. require_once(DOKU_INC.'inc/io.php');
  14. // some ACL level defines
  15. define('AUTH_NONE',0);
  16. define('AUTH_READ',1);
  17. define('AUTH_EDIT',2);
  18. define('AUTH_CREATE',4);
  19. define('AUTH_UPLOAD',8);
  20. define('AUTH_DELETE',16);
  21. define('AUTH_ADMIN',255);
  22. global $conf;
  23. if($conf['useacl']){
  24. require_once(DOKU_INC.'inc/blowfish.php');
  25. require_once(DOKU_INC.'inc/mail.php');
  26. global $auth;
  27. // load the the backend auth functions and instantiate the auth object
  28. if (@file_exists(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php')) {
  29. require_once(DOKU_INC.'inc/auth/basic.class.php');
  30. require_once(DOKU_INC.'inc/auth/'.$conf['authtype'].'.class.php');
  31. $auth_class = "auth_".$conf['authtype'];
  32. if (class_exists($auth_class)) {
  33. $auth = new $auth_class();
  34. if ($auth->success == false) {
  35. // degrade to unauthenticated user
  36. unset($auth);
  37. auth_logoff();
  38. msg($lang['authtempfail'], -1);
  39. }
  40. } else {
  41. nice_die($lang['authmodfailed']);
  42. }
  43. } else {
  44. nice_die($lang['authmodfailed']);
  45. }
  46. }
  47. // do the login either by cookie or provided credentials
  48. if($conf['useacl']){
  49. if($auth){
  50. if (!isset($_REQUEST['u'])) $_REQUEST['u'] = '';
  51. if (!isset($_REQUEST['p'])) $_REQUEST['p'] = '';
  52. if (!isset($_REQUEST['r'])) $_REQUEST['r'] = '';
  53. $_REQUEST['http_credentials'] = false;
  54. if (!$conf['rememberme']) $_REQUEST['r'] = false;
  55. // streamline HTTP auth credentials (IIS/rewrite -> mod_php)
  56. if(isset($_SERVER['HTTP_AUTHORIZATION'])){
  57. list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) =
  58. explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
  59. }
  60. // if no credentials were given try to use HTTP auth (for SSO)
  61. if(empty($_REQUEST['u']) && empty($_COOKIE[DOKU_COOKIE]) && !empty($_SERVER['PHP_AUTH_USER'])){
  62. $_REQUEST['u'] = $_SERVER['PHP_AUTH_USER'];
  63. $_REQUEST['p'] = $_SERVER['PHP_AUTH_PW'];
  64. $_REQUEST['http_credentials'] = true;
  65. }
  66. // apply cleaning
  67. $_REQUEST['u'] = $auth->cleanUser($_REQUEST['u']);
  68. if(isset($_REQUEST['authtok'])){
  69. // when an authentication token is given, trust the session
  70. auth_validateToken($_REQUEST['authtok']);
  71. }elseif(!is_null($auth) && $auth->canDo('external')){
  72. // external trust mechanism in place
  73. $auth->trustExternal($_REQUEST['u'],$_REQUEST['p'],$_REQUEST['r']);
  74. }else{
  75. $evdata = array(
  76. 'user' => $_REQUEST['u'],
  77. 'password' => $_REQUEST['p'],
  78. 'sticky' => $_REQUEST['r'],
  79. 'silent' => $_REQUEST['http_credentials'],
  80. );
  81. $evt = new Doku_Event('AUTH_LOGIN_CHECK',$evdata);
  82. if($evt->advise_before()){
  83. auth_login($evdata['user'],
  84. $evdata['password'],
  85. $evdata['sticky'],
  86. $evdata['silent']);
  87. }
  88. }
  89. }
  90. //load ACL into a global array
  91. global $AUTH_ACL;
  92. if(is_readable(DOKU_CONF.'acl.auth.php')){
  93. $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
  94. //support user wildcard
  95. if(isset($_SERVER['REMOTE_USER'])){
  96. $AUTH_ACL = str_replace('%USER%',$_SERVER['REMOTE_USER'],$AUTH_ACL);
  97. $AUTH_ACL = str_replace('@USER@',$_SERVER['REMOTE_USER'],$AUTH_ACL); //legacy
  98. }
  99. }else{
  100. $AUTH_ACL = array();
  101. }
  102. }
  103. /**
  104. * This tries to login the user based on the sent auth credentials
  105. *
  106. * The authentication works like this: if a username was given
  107. * a new login is assumed and user/password are checked. If they
  108. * are correct the password is encrypted with blowfish and stored
  109. * together with the username in a cookie - the same info is stored
  110. * in the session, too. Additonally a browserID is stored in the
  111. * session.
  112. *
  113. * If no username was given the cookie is checked: if the username,
  114. * crypted password and browserID match between session and cookie
  115. * no further testing is done and the user is accepted
  116. *
  117. * If a cookie was found but no session info was availabe the
  118. * blowfish encrypted password from the cookie is decrypted and
  119. * together with username rechecked by calling this function again.
  120. *
  121. * On a successful login $_SERVER[REMOTE_USER] and $USERINFO
  122. * are set.
  123. *
  124. * @author Andreas Gohr <andi@splitbrain.org>
  125. *
  126. * @param string $user Username
  127. * @param string $pass Cleartext Password
  128. * @param bool $sticky Cookie should not expire
  129. * @param bool $silent Don't show error on bad auth
  130. * @return bool true on successful auth
  131. */
  132. function auth_login($user,$pass,$sticky=false,$silent=false){
  133. global $USERINFO;
  134. global $conf;
  135. global $lang;
  136. global $auth;
  137. $sticky ? $sticky = true : $sticky = false; //sanity check
  138. if (!$auth) return false;
  139. if(!empty($user)){
  140. //usual login
  141. if ($auth->checkPass($user,$pass)){
  142. // make logininfo globally available
  143. $_SERVER['REMOTE_USER'] = $user;
  144. auth_setCookie($user,PMA_blowfish_encrypt($pass,auth_cookiesalt()),$sticky);
  145. return true;
  146. }else{
  147. //invalid credentials - log off
  148. if(!$silent) msg($lang['badlogin'],-1);
  149. auth_logoff();
  150. return false;
  151. }
  152. }else{
  153. // read cookie information
  154. list($user,$sticky,$pass) = auth_getCookie();
  155. // get session info
  156. $session = $_SESSION[DOKU_COOKIE]['auth'];
  157. if($user && $pass){
  158. // we got a cookie - see if we can trust it
  159. if(isset($session) &&
  160. $auth->useSessionCache($user) &&
  161. ($session['time'] >= time()-$conf['auth_security_timeout']) &&
  162. ($session['user'] == $user) &&
  163. ($session['pass'] == $pass) && //still crypted
  164. ($session['buid'] == auth_browseruid()) ){
  165. // he has session, cookie and browser right - let him in
  166. $_SERVER['REMOTE_USER'] = $user;
  167. $USERINFO = $session['info']; //FIXME move all references to session
  168. return true;
  169. }
  170. // no we don't trust it yet - recheck pass but silent
  171. $pass = PMA_blowfish_decrypt($pass,auth_cookiesalt());
  172. return auth_login($user,$pass,$sticky,true);
  173. }
  174. }
  175. //just to be sure
  176. auth_logoff(true);
  177. return false;
  178. }
  179. /**
  180. * Checks if a given authentication token was stored in the session
  181. *
  182. * Will setup authentication data using data from the session if the
  183. * token is correct. Will exit with a 401 Status if not.
  184. *
  185. * @author Andreas Gohr <andi@splitbrain.org>
  186. * @param string $token The authentication token
  187. * @return boolean true (or will exit on failure)
  188. */
  189. function auth_validateToken($token){
  190. if(!$token || $token != $_SESSION[DOKU_COOKIE]['auth']['token']){
  191. // bad token
  192. header("HTTP/1.0 401 Unauthorized");
  193. print 'Invalid auth token - maybe the session timed out';
  194. unset($_SESSION[DOKU_COOKIE]['auth']['token']); // no second chance
  195. exit;
  196. }
  197. // still here? trust the session data
  198. global $USERINFO;
  199. $_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
  200. $USERINFO = $_SESSION[DOKU_COOKIE]['auth']['info'];
  201. return true;
  202. }
  203. /**
  204. * Create an auth token and store it in the session
  205. *
  206. * NOTE: this is completely unrelated to the getSecurityToken() function
  207. *
  208. * @author Andreas Gohr <andi@splitbrain.org>
  209. * @return string The auth token
  210. */
  211. function auth_createToken(){
  212. $token = md5(mt_rand());
  213. @session_start(); // reopen the session if needed
  214. $_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
  215. session_write_close();
  216. return $token;
  217. }
  218. /**
  219. * Builds a pseudo UID from browser and IP data
  220. *
  221. * This is neither unique nor unfakable - still it adds some
  222. * security. Using the first part of the IP makes sure
  223. * proxy farms like AOLs are stil okay.
  224. *
  225. * @author Andreas Gohr <andi@splitbrain.org>
  226. *
  227. * @return string a MD5 sum of various browser headers
  228. */
  229. function auth_browseruid(){
  230. $ip = clientIP(true);
  231. $uid = '';
  232. $uid .= $_SERVER['HTTP_USER_AGENT'];
  233. $uid .= $_SERVER['HTTP_ACCEPT_ENCODING'];
  234. $uid .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  235. $uid .= $_SERVER['HTTP_ACCEPT_CHARSET'];
  236. $uid .= substr($ip,0,strpos($ip,'.'));
  237. return md5($uid);
  238. }
  239. /**
  240. * Creates a random key to encrypt the password in cookies
  241. *
  242. * This function tries to read the password for encrypting
  243. * cookies from $conf['metadir'].'/_htcookiesalt'
  244. * if no such file is found a random key is created and
  245. * and stored in this file.
  246. *
  247. * @author Andreas Gohr <andi@splitbrain.org>
  248. *
  249. * @return string
  250. */
  251. function auth_cookiesalt(){
  252. global $conf;
  253. $file = $conf['metadir'].'/_htcookiesalt';
  254. $salt = io_readFile($file);
  255. if(empty($salt)){
  256. $salt = uniqid(rand(),true);
  257. io_saveFile($file,$salt);
  258. }
  259. return $salt;
  260. }
  261. /**
  262. * Log out the current user
  263. *
  264. * This clears all authentication data and thus log the user
  265. * off. It also clears session data.
  266. *
  267. * @author Andreas Gohr <andi@splitbrain.org>
  268. * @param bool $keepbc - when true, the breadcrumb data is not cleared
  269. */
  270. function auth_logoff($keepbc=false){
  271. global $conf;
  272. global $USERINFO;
  273. global $INFO, $ID;
  274. global $auth;
  275. // make sure the session is writable (it usually is)
  276. @session_start();
  277. if(isset($_SESSION[DOKU_COOKIE]['auth']['user']))
  278. unset($_SESSION[DOKU_COOKIE]['auth']['user']);
  279. if(isset($_SESSION[DOKU_COOKIE]['auth']['pass']))
  280. unset($_SESSION[DOKU_COOKIE]['auth']['pass']);
  281. if(isset($_SESSION[DOKU_COOKIE]['auth']['info']))
  282. unset($_SESSION[DOKU_COOKIE]['auth']['info']);
  283. if(!$keepbc && isset($_SESSION[DOKU_COOKIE]['bc']))
  284. unset($_SESSION[DOKU_COOKIE]['bc']);
  285. if(isset($_SERVER['REMOTE_USER']))
  286. unset($_SERVER['REMOTE_USER']);
  287. $USERINFO=null; //FIXME
  288. if (version_compare(PHP_VERSION, '5.2.0', '>')) {
  289. setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
  290. }else{
  291. setcookie(DOKU_COOKIE,'',time()-600000,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
  292. }
  293. if($auth && $auth->canDo('logoff')){
  294. $auth->logOff();
  295. }
  296. }
  297. /**
  298. * Check if a user is a manager
  299. *
  300. * Should usually be called without any parameters to check the current
  301. * user.
  302. *
  303. * The info is available through $INFO['ismanager'], too
  304. *
  305. * @author Andreas Gohr <andi@splitbrain.org>
  306. * @see auth_isadmin
  307. * @param string user - Username
  308. * @param array groups - List of groups the user is in
  309. * @param bool adminonly - when true checks if user is admin
  310. */
  311. function auth_ismanager($user=null,$groups=null,$adminonly=false){
  312. global $conf;
  313. global $USERINFO;
  314. global $auth;
  315. if (!$auth) return false;
  316. if(is_null($user)) {
  317. if (!isset($_SERVER['REMOTE_USER'])) {
  318. return false;
  319. } else {
  320. $user = $_SERVER['REMOTE_USER'];
  321. }
  322. }
  323. $user = $auth->cleanUser($user);
  324. if(is_null($groups)) $groups = (array) $USERINFO['grps'];
  325. $groups = array_map(array($auth,'cleanGroup'),$groups);
  326. $user = auth_nameencode($user);
  327. // check username against superuser and manager
  328. $superusers = explode(',', $conf['superuser']);
  329. $superusers = array_unique($superusers);
  330. $superusers = array_map('trim', $superusers);
  331. // prepare an array containing only true values for array_map call
  332. $alltrue = array_fill(0, count($superusers), true);
  333. $superusers = array_map('auth_nameencode', $superusers, $alltrue);
  334. // case insensitive?
  335. if(!$auth->isCaseSensitive()){
  336. $superusers = array_map('utf8_strtolower',$superusers);
  337. $user = utf8_strtolower($user);
  338. }
  339. // check user match
  340. if(in_array($user, $superusers)) return true;
  341. // check managers
  342. if(!$adminonly){
  343. $managers = explode(',', $conf['manager']);
  344. $managers = array_unique($managers);
  345. $managers = array_map('trim', $managers);
  346. // prepare an array containing only true values for array_map call
  347. $alltrue = array_fill(0, count($managers), true);
  348. $managers = array_map('auth_nameencode', $managers, $alltrue);
  349. if(!$auth->isCaseSensitive()) $managers = array_map('utf8_strtolower',$managers);
  350. if(in_array($user, $managers)) return true;
  351. }
  352. // check user's groups against superuser and manager
  353. if (!empty($groups)) {
  354. //prepend groups with @ and nameencode
  355. $cnt = count($groups);
  356. for($i=0; $i<$cnt; $i++){
  357. $groups[$i] = '@'.auth_nameencode($groups[$i]);
  358. if(!$auth->isCaseSensitive()){
  359. $groups[$i] = utf8_strtolower($groups[$i]);
  360. }
  361. }
  362. // check groups against superuser and manager
  363. foreach($superusers as $supu)
  364. if(in_array($supu, $groups)) return true;
  365. if(!$adminonly){
  366. foreach($managers as $mana)
  367. if(in_array($mana, $groups)) return true;
  368. }
  369. }
  370. return false;
  371. }
  372. /**
  373. * Check if a user is admin
  374. *
  375. * Alias to auth_ismanager with adminonly=true
  376. *
  377. * The info is available through $INFO['isadmin'], too
  378. *
  379. * @author Andreas Gohr <andi@splitbrain.org>
  380. * @see auth_ismanager
  381. */
  382. function auth_isadmin($user=null,$groups=null){
  383. return auth_ismanager($user,$groups,true);
  384. }
  385. /**
  386. * Convinience function for auth_aclcheck()
  387. *
  388. * This checks the permissions for the current user
  389. *
  390. * @author Andreas Gohr <andi@splitbrain.org>
  391. *
  392. * @param string $id page ID (needs to be resolved and cleaned)
  393. * @return int permission level
  394. */
  395. function auth_quickaclcheck($id){
  396. global $conf;
  397. global $USERINFO;
  398. # if no ACL is used always return upload rights
  399. if(!$conf['useacl']) return AUTH_UPLOAD;
  400. return auth_aclcheck($id,$_SERVER['REMOTE_USER'],$USERINFO['grps']);
  401. }
  402. /**
  403. * Returns the maximum rights a user has for
  404. * the given ID or its namespace
  405. *
  406. * @author Andreas Gohr <andi@splitbrain.org>
  407. *
  408. * @param string $id page ID (needs to be resolved and cleaned)
  409. * @param string $user Username
  410. * @param array $groups Array of groups the user is in
  411. * @return int permission level
  412. */
  413. function auth_aclcheck($id,$user,$groups){
  414. global $conf;
  415. global $AUTH_ACL;
  416. global $auth;
  417. // if no ACL is used always return upload rights
  418. if(!$conf['useacl']) return AUTH_UPLOAD;
  419. if (!$auth) return AUTH_NONE;
  420. //make sure groups is an array
  421. if(!is_array($groups)) $groups = array();
  422. //if user is superuser or in superusergroup return 255 (acl_admin)
  423. if(auth_isadmin($user,$groups)) { return AUTH_ADMIN; }
  424. $ci = '';
  425. if(!$auth->isCaseSensitive()) $ci = 'ui';
  426. $user = $auth->cleanUser($user);
  427. $groups = array_map(array($auth,'cleanGroup'),(array)$groups);
  428. $user = auth_nameencode($user);
  429. //prepend groups with @ and nameencode
  430. $cnt = count($groups);
  431. for($i=0; $i<$cnt; $i++){
  432. $groups[$i] = '@'.auth_nameencode($groups[$i]);
  433. }
  434. $ns = getNS($id);
  435. $perm = -1;
  436. if($user || count($groups)){
  437. //add ALL group
  438. $groups[] = '@ALL';
  439. //add User
  440. if($user) $groups[] = $user;
  441. //build regexp
  442. $regexp = join('|',$groups);
  443. }else{
  444. $regexp = '@ALL';
  445. }
  446. //check exact match first
  447. $matches = preg_grep('/^'.preg_quote($id,'/').'\s+('.$regexp.')\s+/'.$ci,$AUTH_ACL);
  448. if(count($matches)){
  449. foreach($matches as $match){
  450. $match = preg_replace('/#.*$/','',$match); //ignore comments
  451. $acl = preg_split('/\s+/',$match);
  452. if($acl[2] > AUTH_DELETE) $acl[2] = AUTH_DELETE; //no admins in the ACL!
  453. if($acl[2] > $perm){
  454. $perm = $acl[2];
  455. }
  456. }
  457. if($perm > -1){
  458. //we had a match - return it
  459. return $perm;
  460. }
  461. }
  462. //still here? do the namespace checks
  463. if($ns){
  464. $path = $ns.':\*';
  465. }else{
  466. $path = '\*'; //root document
  467. }
  468. do{
  469. $matches = preg_grep('/^'.$path.'\s+('.$regexp.')\s+/'.$ci,$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];
  477. }
  478. }
  479. //we had a match - return it
  480. return $perm;
  481. }
  482. //get next higher namespace
  483. $ns = getNS($ns);
  484. if($path != '\*'){
  485. $path = $ns.':\*';
  486. if($path == ':\*') $path = '\*';
  487. }else{
  488. //we did this already
  489. //looks like there is something wrong with the ACL
  490. //break here
  491. msg('No ACL setup yet! Denying access to everyone.');
  492. return AUTH_NONE;
  493. }
  494. }while(1); //this should never loop endless
  495. //still here? return no permissions
  496. return AUTH_NONE;
  497. }
  498. /**
  499. * Encode ASCII special chars
  500. *
  501. * Some auth backends allow special chars in their user and groupnames
  502. * The special chars are encoded with this function. Only ASCII chars
  503. * are encoded UTF-8 multibyte are left as is (different from usual
  504. * urlencoding!).
  505. *
  506. * Decoding can be done with rawurldecode
  507. *
  508. * @author Andreas Gohr <gohr@cosmocode.de>
  509. * @see rawurldecode()
  510. */
  511. function auth_nameencode($name,$skip_group=false){
  512. global $cache_authname;
  513. $cache =& $cache_authname;
  514. $name = (string) $name;
  515. if (!isset($cache[$name][$skip_group])) {
  516. if($skip_group && $name{0} =='@'){
  517. $cache[$name][$skip_group] = '@'.preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
  518. "'%'.dechex(ord(substr('\\1',-1)))",substr($name,1));
  519. }else{
  520. $cache[$name][$skip_group] = preg_replace('/([\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f])/e',
  521. "'%'.dechex(ord(substr('\\1',-1)))",$name);
  522. }
  523. }
  524. return $cache[$name][$skip_group];
  525. }
  526. /**
  527. * Create a pronouncable password
  528. *
  529. * @author Andreas Gohr <andi@splitbrain.org>
  530. * @link http://www.phpbuilder.com/annotate/message.php3?id=1014451
  531. *
  532. * @return string pronouncable password
  533. */
  534. function auth_pwgen(){
  535. $pw = '';
  536. $c = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
  537. $v = 'aeiou'; //vowels
  538. $a = $c.$v; //both
  539. //use two syllables...
  540. for($i=0;$i < 2; $i++){
  541. $pw .= $c[rand(0, strlen($c)-1)];
  542. $pw .= $v[rand(0, strlen($v)-1)];
  543. $pw .= $a[rand(0, strlen($a)-1)];
  544. }
  545. //... and add a nice number
  546. $pw .= rand(10,99);
  547. return $pw;
  548. }
  549. /**
  550. * Sends a password to the given user
  551. *
  552. * @author Andreas Gohr <andi@splitbrain.org>
  553. *
  554. * @return bool true on success
  555. */
  556. function auth_sendPassword($user,$password){
  557. global $conf;
  558. global $lang;
  559. global $auth;
  560. if (!$auth) return false;
  561. $hdrs = '';
  562. $user = $auth->cleanUser($user);
  563. $userinfo = $auth->getUserData($user);
  564. if(!$userinfo['mail']) return false;
  565. $text = rawLocale('password');
  566. $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
  567. $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
  568. $text = str_replace('@LOGIN@',$user,$text);
  569. $text = str_replace('@PASSWORD@',$password,$text);
  570. $text = str_replace('@TITLE@',$conf['title'],$text);
  571. return mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
  572. $lang['regpwmail'],
  573. $text,
  574. $conf['mailfrom']);
  575. }
  576. /**
  577. * Register a new user
  578. *
  579. * This registers a new user - Data is read directly from $_POST
  580. *
  581. * @author Andreas Gohr <andi@splitbrain.org>
  582. *
  583. * @return bool true on success, false on any error
  584. */
  585. function register(){
  586. global $lang;
  587. global $conf;
  588. global $auth;
  589. if (!$auth) return false;
  590. if(!$_POST['save']) return false;
  591. if(!$auth->canDo('addUser')) return false;
  592. //clean username
  593. $_POST['login'] = trim($auth->cleanUser($_POST['login']));
  594. //clean fullname and email
  595. $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
  596. $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
  597. if( empty($_POST['login']) ||
  598. empty($_POST['fullname']) ||
  599. empty($_POST['email']) ){
  600. msg($lang['regmissing'],-1);
  601. return false;
  602. }
  603. if ($conf['autopasswd']) {
  604. $pass = auth_pwgen(); // automatically generate password
  605. } elseif (empty($_POST['pass']) ||
  606. empty($_POST['passchk'])) {
  607. msg($lang['regmissing'], -1); // complain about missing passwords
  608. return false;
  609. } elseif ($_POST['pass'] != $_POST['passchk']) {
  610. msg($lang['regbadpass'], -1); // complain about misspelled passwords
  611. return false;
  612. } else {
  613. $pass = $_POST['pass']; // accept checked and valid password
  614. }
  615. //check mail
  616. if(!mail_isvalid($_POST['email'])){
  617. msg($lang['regbadmail'],-1);
  618. return false;
  619. }
  620. //okay try to create the user
  621. if(!$auth->triggerUserMod('create', array($_POST['login'],$pass,$_POST['fullname'],$_POST['email']))){
  622. msg($lang['reguexists'],-1);
  623. return false;
  624. }
  625. // create substitutions for use in notification email
  626. $substitutions = array(
  627. 'NEWUSER' => $_POST['login'],
  628. 'NEWNAME' => $_POST['fullname'],
  629. 'NEWEMAIL' => $_POST['email'],
  630. );
  631. if (!$conf['autopasswd']) {
  632. msg($lang['regsuccess2'],1);
  633. notify('', 'register', '', $_POST['login'], false, $substitutions);
  634. return true;
  635. }
  636. // autogenerated password? then send him the password
  637. if (auth_sendPassword($_POST['login'],$pass)){
  638. msg($lang['regsuccess'],1);
  639. notify('', 'register', '', $_POST['login'], false, $substitutions);
  640. return true;
  641. }else{
  642. msg($lang['regmailfail'],-1);
  643. return false;
  644. }
  645. }
  646. /**
  647. * Update user profile
  648. *
  649. * @author Christopher Smith <chris@jalakai.co.uk>
  650. */
  651. function updateprofile() {
  652. global $conf;
  653. global $INFO;
  654. global $lang;
  655. global $auth;
  656. if (!$auth) return false;
  657. if(empty($_POST['save'])) return false;
  658. if(!checkSecurityToken()) return false;
  659. // should not be able to get here without Profile being possible...
  660. if(!$auth->canDo('Profile')) {
  661. msg($lang['profna'],-1);
  662. return false;
  663. }
  664. if ($_POST['newpass'] != $_POST['passchk']) {
  665. msg($lang['regbadpass'], -1); // complain about misspelled passwords
  666. return false;
  667. }
  668. //clean fullname and email
  669. $_POST['fullname'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['fullname']));
  670. $_POST['email'] = trim(preg_replace('/[\x00-\x1f:<>&%,;]+/','',$_POST['email']));
  671. if ((empty($_POST['fullname']) && $auth->canDo('modName')) ||
  672. (empty($_POST['email']) && $auth->canDo('modMail'))) {
  673. msg($lang['profnoempty'],-1);
  674. return false;
  675. }
  676. if (!mail_isvalid($_POST['email']) && $auth->canDo('modMail')){
  677. msg($lang['regbadmail'],-1);
  678. return false;
  679. }
  680. if ($_POST['fullname'] != $INFO['userinfo']['name'] && $auth->canDo('modName')) $changes['name'] = $_POST['fullname'];
  681. if ($_POST['email'] != $INFO['userinfo']['mail'] && $auth->canDo('modMail')) $changes['mail'] = $_POST['email'];
  682. if (!empty($_POST['newpass']) && $auth->canDo('modPass')) $changes['pass'] = $_POST['newpass'];
  683. if (!count($changes)) {
  684. msg($lang['profnochange'], -1);
  685. return false;
  686. }
  687. if ($conf['profileconfirm']) {
  688. if (!$auth->checkPass($_SERVER['REMOTE_USER'], $_POST['oldpass'])) {
  689. msg($lang['badlogin'],-1);
  690. return false;
  691. }
  692. }
  693. if ($result = $auth->triggerUserMod('modify', array($_SERVER['REMOTE_USER'], $changes))) {
  694. // update cookie and session with the changed data
  695. $cookie = base64_decode($_COOKIE[DOKU_COOKIE]);
  696. list($user,$sticky,$pass) = explode('|',$cookie,3);
  697. if ($changes['pass']) $pass = PMA_blowfish_encrypt($changes['pass'],auth_cookiesalt());
  698. auth_setCookie($_SERVER['REMOTE_USER'],$pass,(bool)$sticky);
  699. return true;
  700. }
  701. }
  702. /**
  703. * Send a new password
  704. *
  705. * This function handles both phases of the password reset:
  706. *
  707. * - handling the first request of password reset
  708. * - validating the password reset auth token
  709. *
  710. * @author Benoit Chesneau <benoit@bchesneau.info>
  711. * @author Chris Smith <chris@jalakai.co.uk>
  712. * @author Andreas Gohr <andi@splitbrain.org>
  713. *
  714. * @return bool true on success, false on any error
  715. */
  716. function act_resendpwd(){
  717. global $lang;
  718. global $conf;
  719. global $auth;
  720. if(!actionOK('resendpwd')) return false;
  721. if (!$auth) return false;
  722. // should not be able to get here without modPass being possible...
  723. if(!$auth->canDo('modPass')) {
  724. msg($lang['resendna'],-1);
  725. return false;
  726. }
  727. $token = preg_replace('/[^a-f0-9]+/','',$_REQUEST['pwauth']);
  728. if($token){
  729. // we're in token phase
  730. $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
  731. if(!@file_exists($tfile)){
  732. msg($lang['resendpwdbadauth'],-1);
  733. return false;
  734. }
  735. $user = io_readfile($tfile);
  736. @unlink($tfile);
  737. $userinfo = $auth->getUserData($user);
  738. if(!$userinfo['mail']) {
  739. msg($lang['resendpwdnouser'], -1);
  740. return false;
  741. }
  742. $pass = auth_pwgen();
  743. if (!$auth->triggerUserMod('modify', array($user,array('pass' => $pass)))) {
  744. msg('error modifying user data',-1);
  745. return false;
  746. }
  747. if (auth_sendPassword($user,$pass)) {
  748. msg($lang['resendpwdsuccess'],1);
  749. } else {
  750. msg($lang['regmailfail'],-1);
  751. }
  752. return true;
  753. } else {
  754. // we're in request phase
  755. if(!$_POST['save']) return false;
  756. if (empty($_POST['login'])) {
  757. msg($lang['resendpwdmissing'], -1);
  758. return false;
  759. } else {
  760. $user = trim($auth->cleanUser($_POST['login']));
  761. }
  762. $userinfo = $auth->getUserData($user);
  763. if(!$userinfo['mail']) {
  764. msg($lang['resendpwdnouser'], -1);
  765. return false;
  766. }
  767. // generate auth token
  768. $token = md5(auth_cookiesalt().$user); //secret but user based
  769. $tfile = $conf['cachedir'].'/'.$token{0}.'/'.$token.'.pwauth';
  770. $url = wl('',array('do'=>'resendpwd','pwauth'=>$token),true,'&');
  771. io_saveFile($tfile,$user);
  772. $text = rawLocale('pwconfirm');
  773. $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
  774. $text = str_replace('@FULLNAME@',$userinfo['name'],$text);
  775. $text = str_replace('@LOGIN@',$user,$text);
  776. $text = str_replace('@TITLE@',$conf['title'],$text);
  777. $text = str_replace('@CONFIRM@',$url,$text);
  778. if(mail_send($userinfo['name'].' <'.$userinfo['mail'].'>',
  779. $lang['regpwmail'],
  780. $text,
  781. $conf['mailfrom'])){
  782. msg($lang['resendpwdconfirm'],1);
  783. }else{
  784. msg($lang['regmailfail'],-1);
  785. }
  786. return true;
  787. }
  788. return false; // never reached
  789. }
  790. /**
  791. * Encrypts a password using the given method and salt
  792. *
  793. * If the selected method needs a salt and none was given, a random one
  794. * is chosen.
  795. *
  796. * The following methods are understood:
  797. *
  798. * smd5 - Salted MD5 hashing
  799. * apr1 - Apache salted MD5 hashing
  800. * md5 - Simple MD5 hashing
  801. * sha1 - SHA1 hashing
  802. * ssha - Salted SHA1 hashing
  803. * crypt - Unix crypt
  804. * mysql - MySQL password (old method)
  805. * my411 - MySQL 4.1.1 password
  806. * kmd5 - Salted MD5 hashing as used by UNB
  807. *
  808. * @author Andreas Gohr <andi@splitbrain.org>
  809. * @return string The crypted password
  810. */
  811. function auth_cryptPassword($clear,$method='',$salt=null){
  812. global $conf;
  813. if(empty($method)) $method = $conf['passcrypt'];
  814. //prepare a salt
  815. if(is_null($salt)) $salt = md5(uniqid(rand(), true));
  816. switch(strtolower($method)){
  817. case 'smd5':
  818. if(defined('CRYPT_MD5') && CRYPT_MD5) return crypt($clear,'$1$'.substr($salt,0,8).'$');
  819. // when crypt can't handle SMD5, falls through to pure PHP implementation
  820. $magic = '1';
  821. case 'apr1':
  822. //from http://de.php.net/manual/en/function.crypt.php#73619 comment by <mikey_nich at hotmail dot com>
  823. if(!$magic) $magic = 'apr1';
  824. $salt = substr($salt,0,8);
  825. $len = strlen($clear);
  826. $text = $clear.'$'.$magic.'$'.$salt;
  827. $bin = pack("H32", md5($clear.$salt.$clear));
  828. for($i = $len; $i > 0; $i -= 16) {
  829. $text .= substr($bin, 0, min(16, $i));
  830. }
  831. for($i = $len; $i > 0; $i >>= 1) {
  832. $text .= ($i & 1) ? chr(0) : $clear{0};
  833. }
  834. $bin = pack("H32", md5($text));
  835. for($i = 0; $i < 1000; $i++) {
  836. $new = ($i & 1) ? $clear : $bin;
  837. if ($i % 3) $new .= $salt;
  838. if ($i % 7) $new .= $clear;
  839. $new .= ($i & 1) ? $bin : $clear;
  840. $bin = pack("H32", md5($new));
  841. }
  842. $tmp = '';
  843. for ($i = 0; $i < 5; $i++) {
  844. $k = $i + 6;
  845. $j = $i + 12;
  846. if ($j == 16) $j = 5;
  847. $tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
  848. }
  849. $tmp = chr(0).chr(0).$bin[11].$tmp;
  850. $tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
  851. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  852. "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  853. return '$'.$magic.'$'.$salt.'$'.$tmp;
  854. case 'md5':
  855. return md5($clear);
  856. case 'sha1':
  857. return sha1($clear);
  858. case 'ssha':
  859. $salt=substr($salt,0,4);
  860. return '{SSHA}'.base64_encode(pack("H*", sha1($clear.$salt)).$salt);
  861. case 'crypt':
  862. return crypt($clear,substr($salt,0,2));
  863. case 'mysql':
  864. //from http://www.php.net/mysql comment by <soren at byu dot edu>
  865. $nr=0x50305735;
  866. $nr2=0x12345671;
  867. $add=7;
  868. $charArr = preg_split("//", $clear);
  869. foreach ($charArr as $char) {
  870. if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
  871. $charVal = ord($char);
  872. $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
  873. $nr2 += ($nr2 << 8) ^ $nr;
  874. $add += $charVal;
  875. }
  876. return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
  877. case 'my411':
  878. return '*'.sha1(pack("H*", sha1($clear)));
  879. case 'kmd5':
  880. $key = substr($salt, 16, 2);
  881. $hash1 = strtolower(md5($key . md5($clear)));
  882. $hash2 = substr($hash1, 0, 16) . $key . substr($hash1, 16);
  883. return $hash2;
  884. default:
  885. msg("Unsupported crypt method $method",-1);
  886. }
  887. }
  888. /**
  889. * Verifies a cleartext password against a crypted hash
  890. *
  891. * The method and salt used for the crypted hash is determined automatically
  892. * then the clear text password is crypted using the same method. If both hashs
  893. * match true is is returned else false
  894. *
  895. * @author Andreas Gohr <andi@splitbrain.org>
  896. * @return bool
  897. */
  898. function auth_verifyPassword($clear,$crypt){
  899. $method='';
  900. $salt='';
  901. //determine the used method and salt
  902. $len = strlen($crypt);
  903. if(preg_match('/^\$1\$([^\$]{0,8})\$/',$crypt,$m)){
  904. $method = 'smd5';
  905. $salt = $m[1];
  906. }elseif(preg_match('/^\$apr1\$([^\$]{0,8})\$/',$crypt,$m)){
  907. $method = 'apr1';
  908. $salt = $m[1];
  909. }elseif(substr($crypt,0,6) == '{SSHA}'){
  910. $method = 'ssha';
  911. $salt = substr(base64_decode(substr($crypt, 6)),20);
  912. }elseif($len == 32){
  913. $method = 'md5';
  914. }elseif($len == 40){
  915. $method = 'sha1';
  916. }elseif($len == 16){
  917. $method = 'mysql';
  918. }elseif($len == 41 && $crypt[0] == '*'){
  919. $method = 'my411';
  920. }elseif($len == 34){
  921. $method = 'kmd5';
  922. $salt = $crypt;
  923. }else{
  924. $method = 'crypt';
  925. $salt = substr($crypt,0,2);
  926. }
  927. //crypt and compare
  928. if(auth_cryptPassword($clear,$method,$salt) === $crypt){
  929. return true;
  930. }
  931. return false;
  932. }
  933. /**
  934. * Set the authentication cookie and add user identification data to the session
  935. *
  936. * @param string $user username
  937. * @param string $pass encrypted password
  938. * @param bool $sticky whether or not the cookie will last beyond the session
  939. */
  940. function auth_setCookie($user,$pass,$sticky) {
  941. global $conf;
  942. global $auth;
  943. global $USERINFO;
  944. if (!$auth) return false;
  945. $USERINFO = $auth->getUserData($user);
  946. // set cookie
  947. $cookie = base64_encode($user).'|'.((int) $sticky).'|'.base64_encode($pass);
  948. $time = $sticky ? (time()+60*60*24*365) : 0; //one year
  949. if (version_compare(PHP_VERSION, '5.2.0', '>')) {
  950. setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()),true);
  951. }else{
  952. setcookie(DOKU_COOKIE,$cookie,$time,DOKU_REL,'',($conf['securecookie'] && is_ssl()));
  953. }
  954. // set session
  955. $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
  956. $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
  957. $_SESSION[DOKU_COOKIE]['auth']['buid'] = auth_browseruid();
  958. $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
  959. $_SESSION[DOKU_COOKIE]['auth']['time'] = time();
  960. }
  961. /**
  962. * Returns the user, (encrypted) password and sticky bit from cookie
  963. *
  964. * @returns array
  965. */
  966. function auth_getCookie(){
  967. if (!isset($_COOKIE[DOKU_COOKIE])) {
  968. return array(null, null, null);
  969. }
  970. list($user,$sticky,$pass) = explode('|',$_COOKIE[DOKU_COOKIE],3);
  971. $sticky = (bool) $sticky;
  972. $pass = base64_decode($pass);
  973. $user = base64_decode($user);
  974. return array($user,$sticky,$pass);
  975. }
  976. //Setup VIM: ex: et ts=2 enc=utf-8 :