security2.lib.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. $_SESSION["dol_loginmesg"]=$langs->trans("ErrorFailedToLoadLoginFileForMode",$mode);
  100. }
  101. }
  102. }
  103. }
  104. return $login;
  105. }
  106. /**
  107. * Show Dolibarr default login page.
  108. * Part of this code is also duplicated into main.inc.php::top_htmlhead
  109. *
  110. * @param Translate $langs Lang object (must be initialized by a new).
  111. * @param Conf $conf Conf object
  112. * @param Societe $mysoc Company object
  113. * @return void
  114. */
  115. function dol_loginfunction($langs,$conf,$mysoc)
  116. {
  117. global $dolibarr_main_demo,$db;
  118. global $smartphone,$hookmanager;
  119. // Instantiate hooks of thirdparty module only if not already define
  120. $hookmanager->initHooks(array('mainloginpage'));
  121. $langs->load("main");
  122. $langs->load("other");
  123. $langs->load("help");
  124. $langs->load("admin");
  125. $main_authentication=$conf->file->main_authentication;
  126. $session_name=session_name();
  127. $dol_url_root = DOL_URL_ROOT;
  128. $php_self = $_SERVER['PHP_SELF'];
  129. $php_self.= $_SERVER["QUERY_STRING"]?'?'.$_SERVER["QUERY_STRING"]:'';
  130. if (! preg_match('/mainmenu=/',$php_self)) $php_self.=(preg_match('/\?/',$php_self)?'&':'?').'mainmenu=home';
  131. // Title
  132. $title='Dolibarr '.DOL_VERSION;
  133. if (! empty($conf->global->MAIN_APPLICATION_TITLE)) $title=$conf->global->MAIN_APPLICATION_TITLE;
  134. // Note: $conf->css looks like '/theme/eldy/style.css.php'
  135. $conf->css = "/theme/".(GETPOST('theme')?GETPOST('theme','alpha'):$conf->theme)."/style.css.php";
  136. //$themepath=dol_buildpath((empty($conf->global->MAIN_FORCETHEMEDIR)?'':$conf->global->MAIN_FORCETHEMEDIR).$conf->css,1);
  137. $themepath=dol_buildpath($conf->css,1);
  138. if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application
  139. {
  140. foreach($conf->modules_parts['theme'] as $reldir)
  141. {
  142. if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
  143. {
  144. $themepath=dol_buildpath($reldir.$conf->css, 1);
  145. break;
  146. }
  147. }
  148. }
  149. $conf_css = $themepath."?lang=".$langs->defaultlang;
  150. // Select templates
  151. if (! empty($conf->modules_parts['tpl'])) // Using this feature slow down application
  152. {
  153. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl/'));
  154. foreach($dirtpls as $reldir)
  155. {
  156. $tmp=dol_buildpath($reldir.'login.tpl.php');
  157. if (file_exists($tmp)) { $template_dir=preg_replace('/login\.tpl\.php$/','',$tmp); break; }
  158. }
  159. }
  160. else
  161. {
  162. $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/";
  163. }
  164. // Set cookie for timeout management
  165. $prefix=dol_getprefix();
  166. $sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
  167. if (! empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", '', 0);
  168. if (GETPOST('urlfrom','alpha')) $_SESSION["urlfrom"]=GETPOST('urlfrom','alpha');
  169. else unset($_SESSION["urlfrom"]);
  170. if (! GETPOST("username")) $focus_element='username';
  171. else $focus_element='password';
  172. $login_background=DOL_URL_ROOT.'/theme/login_background.png';
  173. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/login_background.png'))
  174. {
  175. $login_background=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/login_background.png';
  176. }
  177. $demologin='';
  178. $demopassword='';
  179. if (! empty($dolibarr_main_demo))
  180. {
  181. $tab=explode(',',$dolibarr_main_demo);
  182. $demologin=$tab[0];
  183. $demopassword=$tab[1];
  184. }
  185. // Execute hook getLoginPageOptions
  186. // Should be an array with differents options in $hookmanager->resArray
  187. $parameters=array('entity' => GETPOST('entity','int'));
  188. $hookmanager->executeHooks('getLoginPageOptions',$parameters); // Note that $action and $object may have been modified by some hooks
  189. // Login
  190. $login = (! empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username","alpha") ? GETPOST("username","alpha") : $demologin));
  191. $password = $demopassword;
  192. // Show logo (search in order: small company logo, large company logo, theme logo, common logo)
  193. $width=0;
  194. $urllogo=DOL_URL_ROOT.'/theme/login_logo.png';
  195. if (! empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small))
  196. {
  197. $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=companylogo&amp;file='.urlencode('thumbs/'.$mysoc->logo_small);
  198. }
  199. elseif (! empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo))
  200. {
  201. $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=companylogo&amp;file='.urlencode($mysoc->logo);
  202. $width=128;
  203. }
  204. elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png'))
  205. {
  206. $urllogo=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png';
  207. }
  208. elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.png'))
  209. {
  210. $urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png';
  211. }
  212. // Security graphical code
  213. $captcha=0;
  214. $captcha_refresh='';
  215. if (function_exists("imagecreatefrompng") && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
  216. {
  217. $captcha=1;
  218. $captcha_refresh=img_picto($langs->trans("Refresh"),'refresh','id="captcha_refresh_img"');
  219. }
  220. // Extra link
  221. $forgetpasslink=0;
  222. $helpcenterlink=0;
  223. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
  224. {
  225. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK))
  226. {
  227. $forgetpasslink=1;
  228. }
  229. if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
  230. {
  231. $helpcenterlink=1;
  232. }
  233. }
  234. // Home message
  235. $main_home='';
  236. if (! empty($conf->global->MAIN_HOME))
  237. {
  238. $i=0;
  239. while (preg_match('/__\(([a-zA-Z|@]+)\)__/i',$conf->global->MAIN_HOME,$reg) && $i < 100)
  240. {
  241. $tmp=explode('|',$reg[1]);
  242. if (! empty($tmp[1])) $langs->load($tmp[1]);
  243. $conf->global->MAIN_HOME=preg_replace('/__\('.preg_quote($reg[1]).'\)__/i',$langs->trans($tmp[0]),$conf->global->MAIN_HOME);
  244. $i++;
  245. }
  246. $main_home=dol_htmlcleanlastbr($conf->global->MAIN_HOME);
  247. }
  248. // Google AD
  249. $main_google_ad_client = ((! empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && ! empty($conf->global->MAIN_GOOGLE_AD_SLOT))?1:0);
  250. // Set jquery theme
  251. $dol_loginmesg = (! empty($_SESSION["dol_loginmesg"])?$_SESSION["dol_loginmesg"]:'');
  252. $favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
  253. if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
  254. $jquerytheme = 'smoothness';
  255. if (! empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
  256. // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_nomousehover
  257. $dol_hide_topmenu=GETPOST('dol_hide_topmenu');
  258. $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu');
  259. $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen');
  260. $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover');
  261. $dol_use_jmobile=GETPOST('dol_use_jmobile');
  262. // Include login page template
  263. include $template_dir.'login.tpl.php';
  264. $_SESSION["dol_loginmesg"] = '';
  265. }
  266. /**
  267. * Fonction pour initialiser un salt pour la fonction crypt.
  268. *
  269. * @param int $type 2=>renvoi un salt pour cryptage DES
  270. * 12=>renvoi un salt pour cryptage MD5
  271. * non defini=>renvoi un salt pour cryptage par defaut
  272. * @return string Salt string
  273. */
  274. function makesalt($type=CRYPT_SALT_LENGTH)
  275. {
  276. dol_syslog("makesalt type=".$type);
  277. switch($type)
  278. {
  279. case 12: // 8 + 4
  280. $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
  281. case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise)
  282. $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
  283. case 2: // 2
  284. default: // by default, fall back on Standard DES (should work everywhere)
  285. $saltlen=2; $saltprefix=''; $saltsuffix=''; break;
  286. }
  287. $salt='';
  288. while(dol_strlen($salt) < $saltlen) $salt.=chr(mt_rand(64,126));
  289. $result=$saltprefix.$salt.$saltsuffix;
  290. dol_syslog("makesalt return=".$result);
  291. return $result;
  292. }
  293. /**
  294. * Encode or decode database password in config file
  295. *
  296. * @param int $level Encode level: 0 no encoding, 1 encoding
  297. * @return int <0 if KO, >0 if OK
  298. */
  299. function encodedecode_dbpassconf($level=0)
  300. {
  301. dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG);
  302. $config = '';
  303. $passwd='';
  304. $passwd_crypted='';
  305. if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','r'))
  306. {
  307. while(!feof($fp))
  308. {
  309. $buffer = fgets($fp,4096);
  310. $lineofpass=0;
  311. if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i',$buffer,$reg)) // Old way to save crypted value
  312. {
  313. $val = trim($reg[1]); // This also remove CR/LF
  314. $val=preg_replace('/^["\']/','',$val);
  315. $val=preg_replace('/["\'][\s;]*$/','',$val);
  316. if (! empty($val))
  317. {
  318. $passwd_crypted = $val;
  319. $val = dol_decode($val);
  320. $passwd = $val;
  321. $lineofpass=1;
  322. }
  323. }
  324. elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i',$buffer,$reg))
  325. {
  326. $val = trim($reg[1]); // This also remove CR/LF
  327. $val=preg_replace('/^["\']/','',$val);
  328. $val=preg_replace('/["\'][\s;]*$/','',$val);
  329. if (preg_match('/crypted:/i',$buffer))
  330. {
  331. $val = preg_replace('/crypted:/i','',$val);
  332. $passwd_crypted = $val;
  333. $val = dol_decode($val);
  334. $passwd = $val;
  335. }
  336. else
  337. {
  338. $passwd = $val;
  339. $val = dol_encode($val);
  340. $passwd_crypted = $val;
  341. }
  342. $lineofpass=1;
  343. }
  344. // Output line
  345. if ($lineofpass)
  346. {
  347. // Add value at end of file
  348. if ($level == 0)
  349. {
  350. $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n";
  351. }
  352. if ($level == 1)
  353. {
  354. $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n";
  355. }
  356. //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted;
  357. //exit;
  358. }
  359. else
  360. {
  361. $config .= $buffer;
  362. }
  363. }
  364. fclose($fp);
  365. // Write new conf file
  366. $file=DOL_DOCUMENT_ROOT.'/conf/conf.php';
  367. if ($fp = @fopen($file,'w'))
  368. {
  369. fputs($fp, $config);
  370. fclose($fp);
  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 (a MD5 string), 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. }