dolibarr  16.0.5
security2.lib.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2008-2017 Regis Houssin <regis.houssin@inodbox.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 <https://www.gnu.org/licenses/>.
17  * or see https://www.gnu.org/
18  */
19 
35 function dol_getwebuser($mode)
36 {
37  $t = '?';
38  if ($mode == 'user') {
39  $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty
40  }
41  if ($mode == 'group') {
42  $t = getenv('APACHE_RUN_GROUP');
43  }
44  return $t;
45 }
46 
57 function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context = '')
58 {
59  global $conf, $langs;
60  //global $dolauthmode; // To return authentication finally used
61 
62  // Check parameters
63  if ($entitytotest == '') {
64  $entitytotest = 1;
65  }
66 
67  dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode));
68  $login = '';
69 
70  // Validation of login/pass/entity with standard modules
71  if (empty($login)) {
72  $test = true;
73  foreach ($authmode as $mode) {
74  if ($test && $mode && !$login) {
75  // Validation of login/pass/entity for mode $mode
76  $mode = trim($mode);
77  $authfile = 'functions_'.$mode.'.php';
78  $fullauthfile = '';
79 
80  $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']);
81  foreach ($dirlogin as $reldir) {
82  $dir = dol_buildpath($reldir, 0);
83  $newdir = dol_osencode($dir);
84 
85  // Check if file found (do not use dol_is_file to avoid loading files.lib.php)
86  $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile;
87  if (is_file($tmpnewauthfile)) {
88  $fullauthfile = $tmpnewauthfile;
89  }
90  }
91 
92  $result = false;
93  if ($fullauthfile) {
94  $result = include_once $fullauthfile;
95  }
96  if ($fullauthfile && $result) {
97  // Call function to check user/password
98  $function = 'check_user_password_'.$mode;
99  $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context);
100  if ($login && $login != '--bad-login-validity--') { // Login is successfull
101  $test = false; // To stop once at first login success
102  $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used
103  $dol_tz = GETPOST('tz');
104  $dol_dst = GETPOST('dst');
105  $dol_screenwidth = GETPOST('screenwidth');
106  $dol_screenheight = GETPOST('screenheight');
107  }
108  } else {
109  dol_syslog("Authentication KO - failed to load file '".$authfile."'", LOG_ERR);
110  sleep(1);
111  // Load translation files required by the page
112  $langs->loadLangs(array('other', 'main', 'errors'));
113 
114  $_SESSION["dol_loginmesg"] = (empty($_SESSION["dol_loginmesg"]) ? '' : $_SESSION["dol_loginmesg"].', ').$langs->transnoentitiesnoconv("ErrorFailedToLoadLoginFileForMode", $mode);
115  }
116  }
117  }
118  }
119 
120  return $login;
121 }
122 
123 
124 if (!function_exists('dol_loginfunction')) {
134  function dol_loginfunction($langs, $conf, $mysoc)
135  {
136  global $dolibarr_main_demo, $dolibarr_main_force_https;
137  global $db, $hookmanager;
138 
139  $langs->loadLangs(array("main", "other", "help", "admin"));
140 
141  // Instantiate hooks of thirdparty module only if not already define
142  $hookmanager->initHooks(array('mainloginpage'));
143 
144  $main_authentication = $conf->file->main_authentication;
145 
146  $session_name = session_name(); // Get current session name
147 
148  $dol_url_root = DOL_URL_ROOT;
149 
150  // Title
151  $appli = constant('DOL_APPLICATION_TITLE');
152  $title = $appli.' '.constant('DOL_VERSION');
153  if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
154  $title = $conf->global->MAIN_APPLICATION_TITLE;
155  }
156  $titletruedolibarrversion = constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version
157 
158  // Note: $conf->css looks like '/theme/eldy/style.css.php'
159  /*
160  $conf->css = "/theme/".(GETPOST('theme','aZ09')?GETPOST('theme','aZ09'):$conf->theme)."/style.css.php";
161  $themepath=dol_buildpath($conf->css,1);
162  if (! empty($conf->modules_parts['theme'])) // Using this feature slow down application
163  {
164  foreach($conf->modules_parts['theme'] as $reldir)
165  {
166  if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
167  {
168  $themepath=dol_buildpath($reldir.$conf->css, 1);
169  break;
170  }
171  }
172  }
173  $conf_css = $themepath."?lang=".$langs->defaultlang;
174  */
175 
176  // Select templates dir
177  if (!empty($conf->modules_parts['tpl'])) { // Using this feature slow down application
178  $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl/'));
179  foreach ($dirtpls as $reldir) {
180  $tmp = dol_buildpath($reldir.'login.tpl.php');
181  if (file_exists($tmp)) {
182  $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp);
183  break;
184  }
185  }
186  } else {
187  $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/";
188  }
189 
190  // Set cookie for timeout management. We set it as a cookie so we will be able to use it to set timeout on next page before the session start
191  // and the conf file is loaded.
192  $prefix = dol_getprefix('');
193  $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
194  if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) {
195  setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true);
196  }
197 
198  if (GETPOST('urlfrom', 'alpha')) {
199  $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha');
200  } else {
201  unset($_SESSION["urlfrom"]);
202  }
203 
204  if (!GETPOST("username", 'alpha')) {
205  $focus_element = 'username';
206  } else {
207  $focus_element = 'password';
208  }
209 
210  $demologin = '';
211  $demopassword = '';
212  if (!empty($dolibarr_main_demo)) {
213  $tab = explode(',', $dolibarr_main_demo);
214  $demologin = $tab[0];
215  $demopassword = $tab[1];
216  }
217 
218  // Execute hook getLoginPageOptions (for table)
219  $parameters = array('entity' => GETPOST('entity', 'int'), 'switchentity' => GETPOST('switchentity', 'int'));
220  $reshook = $hookmanager->executeHooks('getLoginPageOptions', $parameters); // Note that $action and $object may have been modified by some hooks.
221  $morelogincontent = $hookmanager->resPrint;
222 
223  // Execute hook getLoginPageExtraOptions (eg for js)
224  $parameters = array('entity' => GETPOST('entity', 'int'), 'switchentity' => GETPOST('switchentity', 'int'));
225  $reshook = $hookmanager->executeHooks('getLoginPageExtraOptions', $parameters); // Note that $action and $object may have been modified by some hooks.
226  $moreloginextracontent = $hookmanager->resPrint;
227 
228  //Redirect after connection
229  $parameters = array('entity' => GETPOST('entity', 'int'), 'switchentity' => GETPOST('switchentity', 'int'));
230  $reshook = $hookmanager->executeHooks('redirectAfterConnection', $parameters); // Note that $action and $object may have been modified by some hooks.
231  $php_self = $hookmanager->resPrint;
232 
233  // Login
234  $login = (!empty($hookmanager->resArray['username']) ? $hookmanager->resArray['username'] : (GETPOST("username", "alpha") ? GETPOST("username", "alpha") : $demologin));
235  $password = $demopassword;
236 
237  // Show logo (search in order: small company logo, large company logo, theme logo, common logo)
238  $width = 0;
239  $urllogo = DOL_URL_ROOT.'/theme/common/login_logo.png';
240 
241  if (!empty($mysoc->logo_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) {
242  $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_small);
243  } elseif (!empty($mysoc->logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) {
244  $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/'.$mysoc->logo);
245  $width = 128;
246  } elseif (!empty($mysoc->logo_squarred_small) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_squarred_small)) {
247  $urllogo = DOL_URL_ROOT.'/viewimage.php?cache=1&amp;modulepart=mycompany&amp;file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_small);
248  } elseif (is_readable(DOL_DOCUMENT_ROOT.'/theme/dolibarr_logo.svg')) {
249  $urllogo = DOL_URL_ROOT.'/theme/dolibarr_logo.svg';
250  }
251 
252  // Security graphical code
253  $captcha = 0;
254  $captcha_refresh = '';
255  if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) {
256  $captcha = 1;
257  $captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"');
258  }
259 
260  // Extra link
261  $forgetpasslink = 0;
262  $helpcenterlink = 0;
263  if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) {
264  if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) {
265  $forgetpasslink = 1;
266  }
267 
268  if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) {
269  $helpcenterlink = 1;
270  }
271  }
272 
273  // Home message
274  $main_home = '';
275  if (!empty($conf->global->MAIN_HOME)) {
276  $substitutionarray = getCommonSubstitutionArray($langs);
277  complete_substitutions_array($substitutionarray, $langs);
278  $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs);
279 
280  $main_home = dol_htmlcleanlastbr($texttoshow);
281  }
282 
283  // Google AD
284  $main_google_ad_client = ((!empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) ? 1 : 0);
285 
286  // Set jquery theme
287  $dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : '');
288 
289  $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png';
290  if (!empty($mysoc->logo_squarred_mini)) {
291  $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini);
292  }
293  if (!empty($conf->global->MAIN_FAVICON_URL)) {
294  $favicon = $conf->global->MAIN_FAVICON_URL;
295  }
296 
297  $jquerytheme = 'base';
298  if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) {
299  $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
300  }
301 
302  // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover
303  $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int');
304  $dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int');
305  $dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int');
306  $dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int');
307  $dol_use_jmobile = GETPOST('dol_use_jmobile', 'int');
308 
309  // Include login page template
310  include $template_dir.'login.tpl.php';
311 
312  // Global html output events ($mesgs, $errors, $warnings)
314 
315  $_SESSION["dol_loginmesg"] = '';
316  }
317 }
318 
327 function makesalt($type = CRYPT_SALT_LENGTH)
328 {
329  dol_syslog("makesalt type=".$type);
330  switch ($type) {
331  case 12: // 8 + 4
332  $saltlen = 8;
333  $saltprefix = '$1$';
334  $saltsuffix = '$';
335  break;
336  case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise)
337  $saltlen = 8;
338  $saltprefix = '$1$';
339  $saltsuffix = '$';
340  break;
341  case 2: // 2
342  default: // by default, fall back on Standard DES (should work everywhere)
343  $saltlen = 2;
344  $saltprefix = '';
345  $saltsuffix = '';
346  break;
347  }
348  $salt = '';
349  while (dol_strlen($salt) < $saltlen) {
350  $salt .= chr(mt_rand(64, 126));
351  }
352 
353  $result = $saltprefix.$salt.$saltsuffix;
354  dol_syslog("makesalt return=".$result);
355  return $result;
356 }
357 
364 function encodedecode_dbpassconf($level = 0)
365 {
366  dol_syslog("encodedecode_dbpassconf level=".$level, LOG_DEBUG);
367  $config = '';
368  $passwd = '';
369  $passwd_crypted = '';
370 
371  if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) {
372  while (!feof($fp)) {
373  $buffer = fgets($fp, 4096);
374 
375  $lineofpass = 0;
376 
377  if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { // Old way to save crypted value
378  $val = trim($reg[1]); // This also remove CR/LF
379  $val = preg_replace('/^["\']/', '', $val);
380  $val = preg_replace('/["\'][\s;]*$/', '', $val);
381  if (!empty($val)) {
382  $passwd_crypted = $val;
383  $val = dol_decode($val);
384  $passwd = $val;
385  $lineofpass = 1;
386  }
387  } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) {
388  $val = trim($reg[1]); // This also remove CR/LF
389  $val = preg_replace('/^["\']/', '', $val);
390  $val = preg_replace('/["\'][\s;]*$/', '', $val);
391  if (preg_match('/crypted:/i', $buffer)) {
392  $val = preg_replace('/crypted:/i', '', $val);
393  $passwd_crypted = $val;
394  $val = dol_decode($val);
395  $passwd = $val;
396  } else {
397  $passwd = $val;
398  $val = dol_encode($val);
399  $passwd_crypted = $val;
400  }
401  $lineofpass = 1;
402  }
403 
404  // Output line
405  if ($lineofpass) {
406  // Add value at end of file
407  if ($level == 0) {
408  $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n";
409  }
410  if ($level == 1) {
411  $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n";
412  }
413 
414  //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted;
415  //exit;
416  } else {
417  $config .= $buffer;
418  }
419  }
420  fclose($fp);
421 
422  // Write new conf file
423  $file = DOL_DOCUMENT_ROOT.'/conf/conf.php';
424  if ($fp = @fopen($file, 'w')) {
425  fputs($fp, $config);
426  fflush($fp);
427  fclose($fp);
428  clearstatcache();
429 
430  // It's config file, so we set read permission for creator only.
431  // Should set permission to web user and groups for users used by batch
432  //@chmod($file, octdec('0600'));
433 
434  return 1;
435  } else {
436  dol_syslog("encodedecode_dbpassconf Failed to open conf.php file for writing", LOG_WARNING);
437  return -1;
438  }
439  } else {
440  dol_syslog("encodedecode_dbpassconf Failed to read conf.php", LOG_ERR);
441  return -2;
442  }
443 }
444 
454 function getRandomPassword($generic = false, $replaceambiguouschars = null, $length = 32)
455 {
456  global $db, $conf, $langs, $user;
457 
458  $generated_password = '';
459  if ($generic) {
460  $lowercase = "qwertyuiopasdfghjklzxcvbnm";
461  $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP";
462  $numbers = "1234567890";
463  $randomCode = "";
464  $nbofchar = round($length / 3);
465  $nbofcharlast = ($length - 2 * $nbofchar);
466  //var_dump($nbofchar.'-'.$nbofcharlast);
467  if (function_exists('random_int')) { // Cryptographic random
468  $max = strlen($lowercase) - 1;
469  for ($x = 0; $x < $nbofchar; $x++) {
470  $tmp = random_int(0, $max);
471  $randomCode .= $lowercase[$tmp];
472  }
473  $max = strlen($uppercase) - 1;
474  for ($x = 0; $x < $nbofchar; $x++) {
475  $tmp = random_int(0, $max);
476  $randomCode .= $uppercase[$tmp];
477  }
478  $max = strlen($numbers) - 1;
479  for ($x = 0; $x < $nbofcharlast; $x++) {
480  $tmp = random_int(0, $max);
481  $randomCode .= $numbers[$tmp];
482  }
483 
484  $generated_password = str_shuffle($randomCode);
485  } else {
486  // Old platform, non cryptographic random
487  $max = strlen($lowercase) - 1;
488  for ($x = 0; $x < $nbofchar; $x++) {
489  $tmp = mt_rand(0, $max);
490  $randomCode .= $lowercase[$tmp];
491  }
492  $max = strlen($uppercase) - 1;
493  for ($x = 0; $x < $nbofchar; $x++) {
494  $tmp = mt_rand(0, $max);
495  $randomCode .= $uppercase[$tmp];
496  }
497  $max = strlen($numbers) - 1;
498  for ($x = 0; $x < $nbofcharlast; $x++) {
499  $tmp = mt_rand(0, $max);
500  $randomCode .= $numbers[$tmp];
501  }
502 
503  $generated_password = str_shuffle($randomCode);
504  }
505  } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) {
506  $nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED);
507  $nomfichier = $nomclass.".class.php";
508  //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass;
509  require_once DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomfichier;
510  $genhandler = new $nomclass($db, $conf, $langs, $user);
511  $generated_password = $genhandler->getNewGeneratedPassword();
512  unset($genhandler);
513  }
514 
515  // Do we have to discard some alphabetic characters ?
516  if (is_array($replaceambiguouschars) && count($replaceambiguouschars) > 0) {
517  $numbers = "ABCDEF";
518  $max = strlen($numbers) - 1;
519  if (function_exists('random_int')) { // Cryptographic random
520  $tmp = random_int(0, $max);
521  $generated_password = str_replace($replaceambiguouschars, $numbers[$tmp], $generated_password);
522  } else {
523  $tmp = mt_rand(0, $max);
524  $generated_password = str_replace($replaceambiguouschars, $numbers[$tmp], $generated_password);
525  }
526  }
527 
528  return $generated_password;
529 }
make_substitutions
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
Definition: functions.lib.php:7839
dol_htmloutput_events
dol_htmloutput_events($disabledoutputofmessages=0)
Print formated messages to output (Used to show messages on html output).
Definition: functions.lib.php:8172
makesalt
if(!function_exists('dol_loginfunction')) makesalt($type=CRYPT_SALT_LENGTH)
Fonction pour initialiser un salt pour la fonction crypt.
Definition: security2.lib.php:327
dol_osencode
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
Definition: functions.lib.php:8499
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
encodedecode_dbpassconf
encodedecode_dbpassconf($level=0)
Encode or decode database password in config file.
Definition: security2.lib.php:364
getRandomPassword
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
Definition: security2.lib.php:454
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
getCommonSubstitutionArray
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
Definition: functions.lib.php:7275
checkLoginPassEntity
checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context='')
Return a login if login/pass was successfull.
Definition: security2.lib.php:57
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
conf
conf($dolibarr_main_document_root)
Load conf file (file must exists)
Definition: inc.php:300
dol_htmlcleanlastbr
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
Definition: functions.lib.php:7036
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
dol_encode
dol_encode($chain, $key='1')
Encode a string with base 64 algorithm + specific delta change.
Definition: security.lib.php:38
$dol_url_root
if($reshook< 0) if(empty($reshook)) $dol_url_root
View.
Definition: passwordforgotten.php:174
dol_getwebuser
dol_getwebuser($mode)
Return user/group account of web server.
Definition: security2.lib.php:35
complete_substitutions_array
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
Definition: functions.lib.php:7961
dol_decode
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
Definition: security.lib.php:69