security2.lib.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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($conf->css,1);
  140. if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application
  141. {
  142. foreach($conf->modules_parts['theme'] as $reldir)
  143. {
  144. if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
  145. {
  146. $themepath=dol_buildpath($reldir.$conf->css, 1);
  147. break;
  148. }
  149. }
  150. }
  151. $conf_css = $themepath."?lang=".$langs->defaultlang;
  152. // Select templates
  153. if (! empty($conf->modules_parts['tpl'])) // Using this feature slow down application
  154. {
  155. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl/'));
  156. foreach($dirtpls as $reldir)
  157. {
  158. $tmp=dol_buildpath($reldir.'login.tpl.php');
  159. if (file_exists($tmp)) { $template_dir=preg_replace('/login\.tpl\.php$/','',$tmp); break; }
  160. }
  161. }
  162. else
  163. {
  164. $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/";
  165. }
  166. // Set cookie for timeout management
  167. $prefix=dol_getprefix();
  168. $sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
  169. if (! empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", '', 0);
  170. if (GETPOST('urlfrom','alpha')) $_SESSION["urlfrom"]=GETPOST('urlfrom','alpha');
  171. else unset($_SESSION["urlfrom"]);
  172. if (! GETPOST("username")) $focus_element='username';
  173. else $focus_element='password';
  174. $demologin='';
  175. $demopassword='';
  176. if (! empty($dolibarr_main_demo))
  177. {
  178. $tab=explode(',',$dolibarr_main_demo);
  179. $demologin=$tab[0];
  180. $demopassword=$tab[1];
  181. }
  182. // Execute hook getLoginPageOptions
  183. // Should be an array with differents options in $hookmanager->resArray
  184. $parameters=array('entity' => GETPOST('entity','int'));
  185. $reshook = $hookmanager->executeHooks('getLoginPageOptions',$parameters); // Note that $action and $object may have been modified by some hooks. resArray is filled by hook.
  186. // Login
  187. $login = (! empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username","alpha") ? GETPOST("username","alpha") : $demologin));
  188. $password = $demopassword;
  189. // Show logo (search in order: small company logo, large company logo, theme logo, common logo)
  190. $width=0;
  191. $urllogo=DOL_URL_ROOT.'/theme/login_logo.png';
  192. if (! empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small))
  193. {
  194. $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('thumbs/'.$mysoc->logo_small);
  195. }
  196. elseif (! empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo))
  197. {
  198. $urllogo=DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode($mysoc->logo);
  199. $width=128;
  200. }
  201. elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png'))
  202. {
  203. $urllogo=DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/dolibarr_logo.png';
  204. }
  205. elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.png'))
  206. {
  207. $urllogo=DOL_URL_ROOT.'/theme/dolibarr_logo.png';
  208. }
  209. // Security graphical code
  210. $captcha=0;
  211. $captcha_refresh='';
  212. if (function_exists("imagecreatefrompng") && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
  213. {
  214. $captcha=1;
  215. $captcha_refresh=img_picto($langs->trans("Refresh"),'refresh','id="captcha_refresh_img"');
  216. }
  217. // Extra link
  218. $forgetpasslink=0;
  219. $helpcenterlink=0;
  220. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
  221. {
  222. if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK))
  223. {
  224. $forgetpasslink=1;
  225. }
  226. if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK))
  227. {
  228. $helpcenterlink=1;
  229. }
  230. }
  231. // Home message
  232. $main_home='';
  233. if (! empty($conf->global->MAIN_HOME))
  234. {
  235. $i=0;
  236. while (preg_match('/__\(([a-zA-Z|@]+)\)__/i',$conf->global->MAIN_HOME,$reg) && $i < 100)
  237. {
  238. $tmp=explode('|',$reg[1]);
  239. if (! empty($tmp[1])) $langs->load($tmp[1]);
  240. $conf->global->MAIN_HOME=preg_replace('/__\('.preg_quote($reg[1]).'\)__/i',$langs->trans($tmp[0]),$conf->global->MAIN_HOME);
  241. $i++;
  242. }
  243. $main_home=dol_htmlcleanlastbr($conf->global->MAIN_HOME);
  244. }
  245. // Google AD
  246. $main_google_ad_client = ((! empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && ! empty($conf->global->MAIN_GOOGLE_AD_SLOT))?1:0);
  247. // Set jquery theme
  248. $dol_loginmesg = (! empty($_SESSION["dol_loginmesg"])?$_SESSION["dol_loginmesg"]:'');
  249. $favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
  250. if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
  251. $jquerytheme = 'smoothness';
  252. if (! empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
  253. // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover
  254. $dol_hide_topmenu=GETPOST('dol_hide_topmenu','int');
  255. $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int');
  256. $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int');
  257. $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int');
  258. $dol_use_jmobile=GETPOST('dol_use_jmobile','int');
  259. // Include login page template
  260. include $template_dir.'login.tpl.php';
  261. $_SESSION["dol_loginmesg"] = '';
  262. }
  263. /**
  264. * Fonction pour initialiser un salt pour la fonction crypt.
  265. *
  266. * @param int $type 2=>renvoi un salt pour cryptage DES
  267. * 12=>renvoi un salt pour cryptage MD5
  268. * non defini=>renvoi un salt pour cryptage par defaut
  269. * @return string Salt string
  270. */
  271. function makesalt($type=CRYPT_SALT_LENGTH)
  272. {
  273. dol_syslog("makesalt type=".$type);
  274. switch($type)
  275. {
  276. case 12: // 8 + 4
  277. $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
  278. case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise)
  279. $saltlen=8; $saltprefix='$1$'; $saltsuffix='$'; break;
  280. case 2: // 2
  281. default: // by default, fall back on Standard DES (should work everywhere)
  282. $saltlen=2; $saltprefix=''; $saltsuffix=''; break;
  283. }
  284. $salt='';
  285. while(dol_strlen($salt) < $saltlen) $salt.=chr(mt_rand(64,126));
  286. $result=$saltprefix.$salt.$saltsuffix;
  287. dol_syslog("makesalt return=".$result);
  288. return $result;
  289. }
  290. /**
  291. * Encode or decode database password in config file
  292. *
  293. * @param int $level Encode level: 0 no encoding, 1 encoding
  294. * @return int <0 if KO, >0 if OK
  295. */
  296. function encodedecode_dbpassconf($level=0)
  297. {
  298. dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG);
  299. $config = '';
  300. $passwd='';
  301. $passwd_crypted='';
  302. if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php','r'))
  303. {
  304. while(!feof($fp))
  305. {
  306. $buffer = fgets($fp,4096);
  307. $lineofpass=0;
  308. if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i',$buffer,$reg)) // Old way to save crypted value
  309. {
  310. $val = trim($reg[1]); // This also remove CR/LF
  311. $val=preg_replace('/^["\']/','',$val);
  312. $val=preg_replace('/["\'][\s;]*$/','',$val);
  313. if (! empty($val))
  314. {
  315. $passwd_crypted = $val;
  316. $val = dol_decode($val);
  317. $passwd = $val;
  318. $lineofpass=1;
  319. }
  320. }
  321. elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i',$buffer,$reg))
  322. {
  323. $val = trim($reg[1]); // This also remove CR/LF
  324. $val=preg_replace('/^["\']/','',$val);
  325. $val=preg_replace('/["\'][\s;]*$/','',$val);
  326. if (preg_match('/crypted:/i',$buffer))
  327. {
  328. $val = preg_replace('/crypted:/i','',$val);
  329. $passwd_crypted = $val;
  330. $val = dol_decode($val);
  331. $passwd = $val;
  332. }
  333. else
  334. {
  335. $passwd = $val;
  336. $val = dol_encode($val);
  337. $passwd_crypted = $val;
  338. }
  339. $lineofpass=1;
  340. }
  341. // Output line
  342. if ($lineofpass)
  343. {
  344. // Add value at end of file
  345. if ($level == 0)
  346. {
  347. $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n";
  348. }
  349. if ($level == 1)
  350. {
  351. $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n";
  352. }
  353. //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted;
  354. //exit;
  355. }
  356. else
  357. {
  358. $config .= $buffer;
  359. }
  360. }
  361. fclose($fp);
  362. // Write new conf file
  363. $file=DOL_DOCUMENT_ROOT.'/conf/conf.php';
  364. if ($fp = @fopen($file,'w'))
  365. {
  366. fputs($fp, $config);
  367. fflush($fp);
  368. fclose($fp);
  369. clearstatcache();
  370. // It's config file, so we set read permission for creator only.
  371. // Should set permission to web user and groups for users used by batch
  372. //@chmod($file, octdec('0600'));
  373. return 1;
  374. }
  375. else
  376. {
  377. dol_syslog("encodedecode_dbpassconf Failed to open conf.php file for writing", LOG_WARNING);
  378. return -1;
  379. }
  380. }
  381. else
  382. {
  383. dol_syslog("encodedecode_dbpassconf Failed to read conf.php", LOG_ERR);
  384. return -2;
  385. }
  386. }
  387. /**
  388. * Return a generated password using default module
  389. *
  390. * @param boolean $generic true=Create generic password (use md5, sha1 depending on setup), false=Use the configured password generation module
  391. * @return string New value for password
  392. */
  393. function getRandomPassword($generic=false)
  394. {
  395. global $db,$conf,$langs,$user;
  396. $generated_password='';
  397. if ($generic) $generated_password=dol_hash(mt_rand());
  398. else if (! empty($conf->global->USER_PASSWORD_GENERATED))
  399. {
  400. $nomclass="modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED);
  401. $nomfichier=$nomclass.".class.php";
  402. //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass;
  403. require_once DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomfichier;
  404. $genhandler=new $nomclass($db,$conf,$langs,$user);
  405. $generated_password=$genhandler->getNewGeneratedPassword();
  406. unset($genhandler);
  407. }
  408. return $generated_password;
  409. }