security2.lib.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2008-2012 Regis Houssin <regis.houssin@capnetworks.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. * or see http://www.gnu.org/
  18. */
  19. /**
  20. * \file htdocs/core/lib/security2.lib.php
  21. * \ingroup core
  22. * \brief Set of function used for dolibarr security (not common functions).
  23. * Warning, this file must not depends on other library files, except function.lib.php
  24. * because it is used at low code level.
  25. */
  26. /**
  27. * Return user/group account of web server
  28. *
  29. * @param string $mode 'user' or 'group'
  30. * @return string Return user or group of web server
  31. */
  32. function dol_getwebuser($mode)
  33. {
  34. $t='?';
  35. if ($mode=='user') $t=getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty
  36. if ($mode=='group') $t=getenv('APACHE_RUN_GROUP');
  37. return $t;
  38. }
  39. /**
  40. * Return a login if login/pass was successfull
  41. *
  42. * @param string $usertotest Login value to test
  43. * @param string $passwordtotest Password value to test
  44. * @param string $entitytotest Instance of data we must check
  45. * @param array $authmode Array list of selected authentication mode array('http', 'dolibarr', 'xxx'...)
  46. * @return string Login or ''
  47. */
  48. function checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode)
  49. {
  50. global $conf,$langs;
  51. //global $dolauthmode; // To return authentication finally used
  52. // Check parameters
  53. if ($entitytotest == '') $entitytotest=1;
  54. dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',',$authmode));
  55. $login = '';
  56. // Validation of login/pass/entity with standard modules
  57. if (empty($login))
  58. {
  59. $test=true;
  60. foreach($authmode as $mode)
  61. {
  62. if ($test && $mode && ! $login)
  63. {
  64. // Validation of login/pass/entity for mode $mode
  65. $mode=trim($mode);
  66. $authfile='functions_'.$mode.'.php';
  67. $fullauthfile='';
  68. $dirlogin=array_merge(array("/core/login"),(array) $conf->modules_parts['login']);
  69. foreach($dirlogin as $reldir)
  70. {
  71. $dir=dol_buildpath($reldir,0);
  72. $newdir=dol_osencode($dir);
  73. // Check if file found (do not use dol_is_file to avoid loading files.lib.php)
  74. if (is_file($newdir.'/'.$authfile)) $fullauthfile=$newdir.'/'.$authfile;
  75. }
  76. $result=false;
  77. if ($fullauthfile) $result=include_once $fullauthfile;
  78. if ($fullauthfile && $result)
  79. {
  80. // Call function to check user/password
  81. $function='check_user_password_'.$mode;
  82. $login=call_user_func($function,$usertotest,$passwordtotest,$entitytotest);
  83. if ($login) // Login is successfull
  84. {
  85. $test=false; // To stop once at first login success
  86. $conf->authmode=$mode; // This properties is defined only when logged to say what mode was successfully used
  87. $dol_tz=GETPOST('tz');
  88. $dol_dst=GETPOST('dst');
  89. $dol_screenwidth=GETPOST('screenwidth');
  90. $dol_screenheight=GETPOST('screenheight');
  91. }
  92. }
  93. else
  94. {
  95. dol_syslog("Authentification ko - failed to load file '".$authfile."'",LOG_ERR);
  96. sleep(1);
  97. $langs->load('main');
  98. $langs->load('other');
  99. $langs->load('errors');
  100. $_SESSION["dol_loginmesg"]=$langs->trans("ErrorFailedToLoadLoginFileForMode",$mode);
  101. }
  102. }
  103. }
  104. }
  105. return $login;
  106. }
  107. /**
  108. * Show Dolibarr default login page.
  109. * Part of this code is also duplicated into main.inc.php::top_htmlhead
  110. *
  111. * @param Translate $langs Lang object (must be initialized by a new).
  112. * @param Conf $conf Conf object
  113. * @param Societe $mysoc Company object
  114. * @return void
  115. */
  116. function dol_loginfunction($langs,$conf,$mysoc)
  117. {
  118. global $dolibarr_main_demo,$db;
  119. global $smartphone,$hookmanager;
  120. // Instantiate hooks of thirdparty module only if not already define
  121. $hookmanager->initHooks(array('mainloginpage'));
  122. $langs->load("main");
  123. $langs->load("other");
  124. $langs->load("help");
  125. $langs->load("admin");
  126. $main_authentication=$conf->file->main_authentication;
  127. $session_name=session_name();
  128. $dol_url_root = DOL_URL_ROOT;
  129. $php_self = $_SERVER['PHP_SELF'];
  130. $php_self.= $_SERVER["QUERY_STRING"]?'?'.$_SERVER["QUERY_STRING"]:'';
  131. if (! preg_match('/mainmenu=/',$php_self)) $php_self.=(preg_match('/\?/',$php_self)?'&':'?').'mainmenu=home';
  132. // Title
  133. $appli=constant('DOL_APPLICATION_TITLE');
  134. $title=$appli.' '.constant('DOL_VERSION');
  135. if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title=$conf->global->MAIN_APPLICATION_TITLE;
  136. $titletruedolibarrversion=constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version
  137. // Note: $conf->css looks like '/theme/eldy/style.css.php'
  138. $conf->css = "/theme/".(GETPOST('theme','alpha')?GETPOST('theme','alpha'):$conf->theme)."/style.css.php";
  139. //$themepath=dol_buildpath((empty($conf->global->MAIN_FORCETHEMEDIR)?'':$conf->global->MAIN_FORCETHEMEDIR).$conf->css,1);
  140. $themepath=dol_buildpath($conf->css,1);
  141. if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application
  142. {
  143. foreach($conf->modules_parts['theme'] as $reldir)
  144. {
  145. if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
  146. {
  147. $themepath=dol_buildpath($reldir.$conf->css, 1);
  148. break;
  149. }
  150. }
  151. }
  152. $conf_css = $themepath."?lang=".$langs->defaultlang;
  153. // Select templates
  154. if (! empty($conf->modules_parts['tpl'])) // Using this feature slow down application
  155. {
  156. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl/'));
  157. foreach($dirtpls as $reldir)
  158. {
  159. $tmp=dol_buildpath($reldir.'login.tpl.php');
  160. if (file_exists($tmp)) { $template_dir=preg_replace('/login\.tpl\.php$/','',$tmp); break; }
  161. }
  162. }
  163. else
  164. {
  165. $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/";
  166. }
  167. // Set cookie for timeout management
  168. $prefix=dol_getprefix();
  169. $sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
  170. if (! empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", '', 0);
  171. if (GETPOST('urlfrom','alpha')) $_SESSION["urlfrom"]=GETPOST('urlfrom','alpha');
  172. else unset($_SESSION["urlfrom"]);
  173. if (! GETPOST("username")) $focus_element='username';
  174. else $focus_element='password';
  175. $demologin='';
  176. $demopassword='';
  177. if (! empty($dolibarr_main_demo))
  178. {
  179. $tab=explode(',',$dolibarr_main_demo);
  180. $demologin=$tab[0];
  181. $demopassword=$tab[1];
  182. }
  183. // Execute hook getLoginPageOptions
  184. // Should be an array with differents options in $hookmanager->resArray
  185. $parameters=array('entity' => GETPOST('entity','int'));
  186. $reshook = $hookmanager->executeHooks('getLoginPageOptions',$parameters); // Note that $action and $object may have been modified by some hooks. resArray is filled by hook.
  187. // Login
  188. $login = (! empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username","alpha") ? GETPOST("username","alpha") : $demologin));
  189. $password = $demopassword;
  190. // Show logo (search in order: small company logo, large company logo, theme logo, common logo)
  191. $width=0;
  192. $urllogo=DOL_URL_ROOT.'/theme/login_logo.png';
  193. if (! empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small))
  194. {
  195. $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('thumbs/'.$mysoc->logo_small);
  196. }
  197. elseif (! empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo))
  198. {
  199. $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode($mysoc->logo);
  200. $width=128;
  201. }
  202. elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png'))
  203. {
  204. $urllogo=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png';
  205. }
  206. elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.png'))
  207. {
  208. $urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png';
  209. }
  210. // Security graphical code
  211. $captcha=0;
  212. $captcha_refresh='';
  213. if (function_exists("imagecreatefrompng") && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
  214. {
  215. $captcha=1;
  216. $captcha_refresh=img_picto($langs->trans("Refresh"),'refresh','id="captcha_refresh_img"');
  217. }
  218. // Extra link
  219. $forgetpasslink=0;
  220. $helpcenterlink=0;
  221. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
  222. {
  223. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK))
  224. {
  225. $forgetpasslink=1;
  226. }
  227. if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
  228. {
  229. $helpcenterlink=1;
  230. }
  231. }
  232. // Home message
  233. $main_home='';
  234. if (! empty($conf->global->MAIN_HOME))
  235. {
  236. $i=0;
  237. while (preg_match('/__\(([a-zA-Z|@]+)\)__/i',$conf->global->MAIN_HOME,$reg) && $i < 100)
  238. {
  239. $tmp=explode('|',$reg[1]);
  240. if (! empty($tmp[1])) $langs->load($tmp[1]);
  241. $conf->global->MAIN_HOME=preg_replace('/__\('.preg_quote($reg[1]).'\)__/i',$langs->trans($tmp[0]),$conf->global->MAIN_HOME);
  242. $i++;
  243. }
  244. $main_home=dol_htmlcleanlastbr($conf->global->MAIN_HOME);
  245. }
  246. // Google AD
  247. $main_google_ad_client = ((! empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && ! empty($conf->global->MAIN_GOOGLE_AD_SLOT))?1:0);
  248. // Set jquery theme
  249. $dol_loginmesg = (! empty($_SESSION["dol_loginmesg"])?$_SESSION["dol_loginmesg"]:'');
  250. $favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
  251. if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
  252. $jquerytheme = 'smoothness';
  253. if (! empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
  254. // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover
  255. $dol_hide_topmenu=GETPOST('dol_hide_topmenu','int');
  256. $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int');
  257. $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int');
  258. $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int');
  259. $dol_use_jmobile=GETPOST('dol_use_jmobile','int');
  260. // Include login page template
  261. include $template_dir.'login.tpl.php';
  262. $_SESSION["dol_loginmesg"] = '';
  263. }
  264. /**
  265. * Fonction pour initialiser un salt pour la fonction crypt.
  266. *
  267. * @param int $type 2=>renvoi un salt pour cryptage DES
  268. * 12=>renvoi un salt pour cryptage MD5
  269. * non defini=>renvoi un salt pour cryptage par defaut
  270. * @return string Salt string
  271. */
  272. function makesalt($type=CRYPT_SALT_LENGTH)
  273. {
  274. dol_syslog("makesalt type=".$type);
  275. switch($type)
  276. {
  277. case 12: // 8 + 4
  278. $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
  279. case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise)
  280. $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
  281. case 2: // 2
  282. default: // by default, fall back on Standard DES (should work everywhere)
  283. $saltlen=2; $saltprefix=''; $saltsuffix=''; break;
  284. }
  285. $salt='';
  286. while(dol_strlen($salt) < $saltlen) $salt.=chr(mt_rand(64,126));
  287. $result=$saltprefix.$salt.$saltsuffix;
  288. dol_syslog("makesalt return=".$result);
  289. return $result;
  290. }
  291. /**
  292. * Encode or decode database password in config file
  293. *
  294. * @param int $level Encode level: 0 no encoding, 1 encoding
  295. * @return int <0 if KO, >0 if OK
  296. */
  297. function encodedecode_dbpassconf($level=0)
  298. {
  299. dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG);
  300. $config = '';
  301. $passwd='';
  302. $passwd_crypted='';
  303. if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','r'))
  304. {
  305. while(!feof($fp))
  306. {
  307. $buffer = fgets($fp,4096);
  308. $lineofpass=0;
  309. if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i',$buffer,$reg)) // Old way to save crypted value
  310. {
  311. $val = trim($reg[1]); // This also remove CR/LF
  312. $val=preg_replace('/^["\']/','',$val);
  313. $val=preg_replace('/["\'][\s;]*$/','',$val);
  314. if (! empty($val))
  315. {
  316. $passwd_crypted = $val;
  317. $val = dol_decode($val);
  318. $passwd = $val;
  319. $lineofpass=1;
  320. }
  321. }
  322. elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i',$buffer,$reg))
  323. {
  324. $val = trim($reg[1]); // This also remove CR/LF
  325. $val=preg_replace('/^["\']/','',$val);
  326. $val=preg_replace('/["\'][\s;]*$/','',$val);
  327. if (preg_match('/crypted:/i',$buffer))
  328. {
  329. $val = preg_replace('/crypted:/i','',$val);
  330. $passwd_crypted = $val;
  331. $val = dol_decode($val);
  332. $passwd = $val;
  333. }
  334. else
  335. {
  336. $passwd = $val;
  337. $val = dol_encode($val);
  338. $passwd_crypted = $val;
  339. }
  340. $lineofpass=1;
  341. }
  342. // Output line
  343. if ($lineofpass)
  344. {
  345. // Add value at end of file
  346. if ($level == 0)
  347. {
  348. $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n";
  349. }
  350. if ($level == 1)
  351. {
  352. $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n";
  353. }
  354. //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted;
  355. //exit;
  356. }
  357. else
  358. {
  359. $config .= $buffer;
  360. }
  361. }
  362. fclose($fp);
  363. // Write new conf file
  364. $file=DOL_DOCUMENT_ROOT.'/conf/conf.php';
  365. if ($fp = @fopen($file,'w'))
  366. {
  367. fputs($fp, $config);
  368. fflush($fp);
  369. fclose($fp);
  370. clearstatcache();
  371. // It's config file, so we set read permission for creator only.
  372. // Should set permission to web user and groups for users used by batch
  373. //@chmod($file, octdec('0600'));
  374. return 1;
  375. }
  376. else
  377. {
  378. dol_syslog("encodedecode_dbpassconf Failed to open conf.php file for writing", LOG_WARNING);
  379. return -1;
  380. }
  381. }
  382. else
  383. {
  384. dol_syslog("encodedecode_dbpassconf Failed to read conf.php", LOG_ERR);
  385. return -2;
  386. }
  387. }
  388. /**
  389. * Return a generated password using default module
  390. *
  391. * @param boolean $generic true=Create generic password (use md5, sha1 depending on setup), false=Use the configured password generation module
  392. * @return string New value for password
  393. */
  394. function getRandomPassword($generic=false)
  395. {
  396. global $db,$conf,$langs,$user;
  397. $generated_password='';
  398. if ($generic) $generated_password=dol_hash(mt_rand());
  399. else if (! empty($conf->global->USER_PASSWORD_GENERATED))
  400. {
  401. $nomclass="modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED);
  402. $nomfichier=$nomclass.".class.php";
  403. //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass;
  404. require_once DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomfichier;
  405. $genhandler=new $nomclass($db,$conf,$langs,$user);
  406. $generated_password=$genhandler->getNewGeneratedPassword();
  407. unset($genhandler);
  408. }
  409. return $generated_password;
  410. }