dolibarr 20.0.0
security.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2022 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2007 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2013-2015 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Load Dolibarr environment
28require '../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
31
32$action = GETPOST('action', 'aZ09');
33
34// Load translation files required by the page
35$langs->loadLangs(array("users", "admin", "other"));
36
37if (!$user->admin) {
39}
40
41// Allow/Disallow change to clear passwords once passwords are encrypted
42$allow_disable_encryption = false;
43
44
45/*
46 * Actions
47 */
48
49if ($action == 'setgeneraterule') {
50 if (!dolibarr_set_const($db, 'USER_PASSWORD_GENERATED', GETPOST("value", "alphanohtml"), 'chaine', 0, '', $conf->entity)) {
51 dol_print_error($db);
52 }
53}
54
55if ($action == 'activate_encrypt') {
56 $error = 0;
57
58 $db->begin();
59
60 // On old version, a bug created the constant into user entity, so we delete it to be sure such entry won't exists. We want it in entity 0 or nowhere.
61 dolibarr_del_const($db, "DATABASE_PWD_ENCRYPTED", $conf->entity);
62 // We set entity=0 (all) because DATABASE_PWD_ENCRYPTED is a setup into conf file, so always shared for everybody
63 $entityforall = 0;
64 dolibarr_set_const($db, "DATABASE_PWD_ENCRYPTED", "1", 'chaine', 0, '', $entityforall);
65
66 $sql = "SELECT u.rowid, u.pass, u.pass_crypted";
67 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
68 $sql .= " WHERE u.pass IS NOT NULL AND LENGTH(u.pass) < 32"; // Not a MD5 value
69
70 $resql = $db->query($sql);
71 if ($resql) {
72 $numrows = $db->num_rows($resql);
73 $i = 0;
74 while ($i < $numrows) {
75 $obj = $db->fetch_object($resql);
76 if (dol_hash($obj->pass)) {
77 $sql = "UPDATE ".MAIN_DB_PREFIX."user";
78 $sql .= " SET pass_crypted = '".dol_hash($obj->pass)."', pass = NULL";
79 $sql .= " WHERE rowid=".((int) $obj->rowid);
80 //print $sql;
81
82 $resql2 = $db->query($sql);
83 if (!$resql2) {
84 dol_print_error($db);
85 $error++;
86 break;
87 }
88
89 $i++;
90 }
91 }
92 } else {
93 dol_print_error($db);
94 }
95
96 //print $error." ".$sql;
97 //exit;
98 if (!$error) {
99 $db->commit();
100 } else {
101 $db->rollback();
102 dol_print_error($db, '');
103 }
104} elseif ($action == 'disable_encrypt') {
105 // By default, $allow_disable_encryption is false we do not allow to disable encryption because passwords can't be decoded once encrypted.
106 if ($allow_disable_encryption) {
107 dolibarr_del_const($db, "DATABASE_PWD_ENCRYPTED", $conf->entity);
108 }
109}
110
111if ($action == 'activate_encryptdbpassconf') {
112 $result = encodedecode_dbpassconf(1);
113 if ($result > 0) {
114 sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait.
115
116 // database value not required
117 //dolibarr_set_const($db, "MAIN_DATABASE_PWD_CONFIG_ENCRYPTED", "1");
118 header("Location: security.php");
119 exit;
120 } else {
121 setEventMessages($langs->trans('InstrucToEncodePass', dol_encode($dolibarr_main_db_pass)), null, 'warnings');
122 }
123} elseif ($action == 'disable_encryptdbpassconf') {
124 $result = encodedecode_dbpassconf(0);
125 if ($result > 0) {
126 sleep(3); // Don't know why but we need to wait file is completely saved before making the reload. Even with flush and clearstatcache, we need to wait.
127
128 // database value not required
129 //dolibarr_del_const($db, "MAIN_DATABASE_PWD_CONFIG_ENCRYPTED",$conf->entity);
130 header("Location: security.php");
131 exit;
132 } else {
133 //setEventMessages($langs->trans('InstrucToClearPass', $dolibarr_main_db_pass), null, 'warnings');
134 setEventMessages($langs->trans('InstrucToClearPass', $langs->transnoentitiesnoconv("DatabasePassword")), null, 'warnings');
135 }
136}
137
138if ($action == 'activate_MAIN_SECURITY_DISABLEFORGETPASSLINK') {
139 dolibarr_set_const($db, "MAIN_SECURITY_DISABLEFORGETPASSLINK", '1', 'chaine', 0, '', $conf->entity);
140} elseif ($action == 'disable_MAIN_SECURITY_DISABLEFORGETPASSLINK') {
141 dolibarr_del_const($db, "MAIN_SECURITY_DISABLEFORGETPASSLINK", $conf->entity);
142}
143
144if ($action == 'updatepattern') {
145 $pattern = GETPOST("pattern", "alpha");
146 $explodePattern = explode(';', $pattern); // List of ints separated with ';' containing counts
147
148 $patternInError = false;
149 if ((int) $explodePattern[0] < 1 || (int) $explodePattern[4] < 0) {
150 $patternInError = true;
151 }
152
153 if ((int) $explodePattern[0] < (int) $explodePattern[1] + (int) $explodePattern[2] + (int) $explodePattern[3]) {
154 $patternInError = true;
155 }
156
157 if (!$patternInError) {
158 dolibarr_set_const($db, "USER_PASSWORD_PATTERN", $pattern, 'chaine', 0, '', $conf->entity);
159 setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
160 header("Location: security.php");
161 exit;
162 }
163}
164
165
166
167/*
168 * View
169 */
170
171$form = new Form($db);
172
173$wikihelp = 'EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad';
174llxHeader('', $langs->trans("Passwords"), $wikihelp, '', 0, 0, '', '', '', 'mod-admin page-security');
175
176print load_fiche_titre($langs->trans("SecuritySetup"), '', 'title_setup');
177
178print '<span class="opacitymedium">'.$langs->trans("GeneratedPasswordDesc")."</span><br>\n";
179print "<br>\n";
180
181
182$head = security_prepare_head();
183
184print dol_get_fiche_head($head, 'passwords', '', -1);
185
186print '<br>';
187
188// Select manager to generate passwords
189print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
190print '<input type="hidden" name="token" value="'.newToken().'">';
191print '<input type="hidden" name="action" value="update">';
192print '<input type="hidden" name="constname" value="USER_PASSWORD_GENERATED">';
193print '<input type="hidden" name="consttype" value="yesno">';
194
195// Charge tableau des modules generation
196$dir = "../core/modules/security/generate";
197clearstatcache();
198$handle = opendir($dir);
199$i = 1;
200$arrayhandler = array();
201if (is_resource($handle)) {
202 while (($file = readdir($handle)) !== false) {
203 if (preg_match('/(modGeneratePass[a-z]+)\.class\.php$/i', $file, $reg)) {
204 // Charging the numbering class
205 $classname = $reg[1];
206 require_once $dir.'/'.$file;
207
208 $obj = new $classname($db, $conf, $langs, $user);
209 '@phan-var-force ModeleGenPassword $obj';
210 $arrayhandler[$obj->id] = $obj;
211 $i++;
212 }
213 }
214 closedir($handle);
215}
216asort($arrayhandler);
217
218print '<div class="div-table-responsive-no-min">';
219print '<table class="noborder centpercent">';
220print '<tr class="liste_titre">';
221print '<td colspan="2">'.$langs->trans("RuleForGeneratedPasswords").'</td>';
222print '<td>'.$langs->trans("Example").'</td>';
223print '<td class="center">'.$langs->trans("Activated").'</td>';
224print '</tr>';
225
226$tabConf = explode(";", getDolGlobalString('USER_PASSWORD_PATTERN'));
227
228foreach ($arrayhandler as $key => $module) {
229 // Show modules according to features level
230 if (!empty($module->version) && $module->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
231 continue;
232 }
233 if (!empty($module->version) && $module->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) {
234 continue;
235 }
236
237 if ($module->isEnabled()) {
238 print '<tr class="oddeven"><td>';
239 print img_picto('', $module->picto, 'class="width25 size15x marginrightonly"').' ';
240 print ucfirst($key);
241 print "</td><td>\n";
242 print $module->getDescription().'<br>';
243 print $langs->trans("MinLength").': <span class="opacitymedium">'.$module->length.'</span>';
244 print '</td>';
245
246 // Show example of numbering module
247 print '<td class="nowraponall">';
248 $tmp = $module->getExample();
249 if (preg_match('/^Error/', $tmp)) {
250 $langs->load("errors");
251 print '<div class="error">'.$langs->trans($tmp).'</div>';
252 } elseif ($tmp == 'NotConfigured') {
253 print '<span class="opacitymedium">'.$langs->trans($tmp).'</span>';
254 } else {
255 print '<span class="opacitymedium">'.$tmp.'</span>';
256 }
257 print '</td>'."\n";
258
259 print '<td class="center">';
260 if ($conf->global->USER_PASSWORD_GENERATED == $key) {
261 //print img_picto('', 'tick');
262 print img_picto($langs->trans("Enabled"), 'switch_on');
263 } else {
264 print '<a href="'.$_SERVER['PHP_SELF'].'?action=setgeneraterule&token='.newToken().'&value='.$key.'">';
265 //print $langs->trans("Activate");
266 print img_picto($langs->trans("Disabled"), 'switch_off');
267 print '</a>';
268 }
269 print "</td></tr>\n";
270 }
271}
272print '</table>';
273print '</div>';
274
275print '</form>';
276
277
278// Pattern for Password Perso
279if (getDolGlobalString('USER_PASSWORD_GENERATED') == "Perso") {
280 print '<br>';
281
282 print '<div class="div-table-responsive-no-min">';
283 print '<table class="noborder centpercent">';
284 print '<tr class="liste_titre">';
285 print '<td colspan="2"> '.$langs->trans("PasswordPatternDesc").'</td>';
286 print '</tr>';
287
288
289 print '<tr class="oddeven">';
290 print '<td>'.$langs->trans("MinLength")."</td>";
291 print '<td><input type="number" class="width50 right" value="'.$tabConf[0].'" id="minlength" min="1"></td>';
292 print '</tr>';
293
294
295 print '<tr class="oddeven">';
296 print '<td>'.$langs->trans("NbMajMin")."</td>";
297 print '<td><input type="number" class="width50 right" value="'.$tabConf[1].'" id="NbMajMin" min="0"></td>';
298 print '</tr>';
299
300
301 print '<tr class="oddeven">';
302 print '<td>'.$langs->trans("NbNumMin")."</td>";
303 print '<td><input type="number" class="width50 right" value="'.$tabConf[2].'" id="NbNumMin" min="0"></td>';
304 print '</tr>';
305
306
307 print '<tr class="oddeven">';
308 print '<td>'.$langs->trans("NbSpeMin")."</td>";
309 print '<td><input type="number" class="width50 right" value="'.$tabConf[3].'" id="NbSpeMin" min="0"></td>';
310 print '</tr>';
311
312
313 print '<tr class="oddeven">';
314 print '<td>'.$langs->trans("NbIteConsecutive")."</td>";
315 print '<td><input type="number" class="width50 right" value="'.$tabConf[4].'" id="NbIteConsecutive" min="0"></td>';
316 print '</tr>';
317
318
319 print '<tr class="oddeven">';
320 print '<td>'.$langs->trans("NoAmbiCaracAutoGeneration")."</td>";
321 print '<td><input type="checkbox" id="NoAmbiCaracAutoGeneration" '.($tabConf[5] ? "checked" : "").' min="0"> <label for="NoAmbiCaracAutoGeneration" id="textcheckbox">'.($tabConf[5] ? $langs->trans("Activated") : $langs->trans("Disabled")).'</label></td>';
322 print '</tr>';
323
324 print '</table>';
325
326 print '<div class="center">';
327 print '<a class="button button-save" id="linkChangePattern">'.$langs->trans("Save").'</a>';
328 print '</div>';
329
330 print '<br><br>';
331
332 print '<script type="text/javascript">';
333 print ' function getStringArg(){';
334 print ' var pattern = "";';
335 print ' pattern += $("#minlenght").val() + ";";';
336 print ' pattern += $("#NbMajMin").val() + ";";';
337 print ' pattern += $("#NbNumMin").val() + ";";';
338 print ' pattern += $("#NbSpeMin").val() + ";";';
339 print ' pattern += $("#NbIteConsecutive").val() + ";";';
340 print ' pattern += $("#NoAmbiCaracAutoGeneration")[0].checked ? "1" : "0";';
341 print ' return pattern;';
342 print ' }';
343
344 print ' function valuePossible(){';
345 print ' var fields = ["#minlenght", "#NbMajMin", "#NbNumMin", "#NbSpeMin", "#NbIteConsecutive"];';
346 print ' for(var i = 0 ; i < fields.length ; i++){';
347 print ' if($(fields[i]).val() < $(fields[i]).attr("min")){';
348 print ' return false;';
349 print ' }';
350 print ' }';
351 print ' ';
352 print ' var length = parseInt($("#minlenght").val());';
353 print ' var length_mini = parseInt($("#NbMajMin").val()) + parseInt($("#NbNumMin").val()) + parseInt($("#NbSpeMin").val());';
354 print ' return length >= length_mini;';
355 print ' }';
356
357 print ' function generatelink(){';
358 print ' return "security.php?action=updatepattern&token='.newToken().'&pattern="+getStringArg();';
359 print ' }';
360
361 print ' function valuePatternChange(){';
362 print ' console.log("valuePatternChange");';
363 print ' var lang_save = "'.$langs->trans("Save").'";';
364 print ' var lang_error = "'.$langs->trans("Error").'";';
365 print ' var lang_Disabled = "'.$langs->trans("Disabled").'";';
366 print ' var lang_Activated = "'.$langs->trans("Activated").'";';
367 print ' $("#textcheckbox").html($("#NoAmbiCaracAutoGeneration")[0].checked ? unescape(lang_Activated) : unescape(lang_Disabled));';
368 print ' if(valuePossible()){';
369 print ' $("#linkChangePattern").attr("href",generatelink()).text(lang_save);';
370 print ' }';
371 print ' else{';
372 print ' $("#linkChangePattern").attr("href", null).text(lang_error);';
373 print ' }';
374 print ' }';
375
376 print ' $("#minlenght").change(function(){valuePatternChange();});';
377 print ' $("#NbMajMin").change(function(){valuePatternChange();});';
378 print ' $("#NbNumMin").change(function(){valuePatternChange();});';
379 print ' $("#NbSpeMin").change(function(){valuePatternChange();});';
380 print ' $("#NbIteConsecutive").change(function(){valuePatternChange();});';
381 print ' $("#NoAmbiCaracAutoGeneration").change(function(){valuePatternChange();});';
382
383 print '</script>';
384}
385
386
387// Crypt passwords in database
388
389print '<br>';
390print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
391print '<input type="hidden" name="token" value="'.newToken().'">';
392print '<input type="hidden" name="action" value="encrypt">';
393
394print '<table class="noborder centpercent">';
395print '<tr class="liste_titre">';
396print '<td colspan="3">'.$langs->trans("Parameters").'</td>';
397print '<td class="center">'.$langs->trans("Activated").'</td>';
398print '<td class="center"></td>';
399print '</tr>';
400
401// Disable clear password in database
402print '<tr class="oddeven">';
403print '<td colspan="3">'.$langs->trans("DoNotStoreClearPassword").'</td>';
404print '<td class="center" width="60">';
405if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
406 print img_picto($langs->trans("Active"), 'tick');
407}
408print '</td>';
409if (!getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
410 print '<td class="center" width="100">';
411 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_encrypt&token='.newToken().'">'.$langs->trans("Activate").'</a>';
412 print "</td>";
413} else {
414 print '<td class="center" width="100">';
415 if ($allow_disable_encryption) {
416 //On n'autorise pas l'annulation de l'encryption car les mots de passe ne peuvent pas etre decodes
417 //Do not allow "disable encryption" as passwords cannot be decrypted
418 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=disable_encrypt&token='.newToken().'">'.$langs->trans("Disable").'</a>';
419 } else {
420 print '<span class="opacitymedium">'.$langs->trans("Always").'</span>';
421 }
422 print "</td>";
423}
424print "</td>";
425print '</tr>';
426
427
428// Crypt password into config file conf.php
429
430print '<tr class="oddeven">';
431print '<td colspan="3">'.$langs->trans("MainDbPasswordFileConfEncrypted").'</td>';
432print '<td align="center" width="60">';
433if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) {
434 print img_picto($langs->trans("Active"), 'tick');
435}
436
437print '</td>';
438
439print '<td class="center" width="100">';
440if (empty($dolibarr_main_db_pass) && empty($dolibarr_main_db_encrypted_pass)) {
441 $langs->load("errors");
442 print img_warning($langs->trans("WarningPassIsEmpty"));
443} else {
444 if (empty($dolibarr_main_db_encrypted_pass)) {
445 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_encryptdbpassconf&token='.newToken().'">'.$langs->trans("Activate").'</a>';
446 }
447 if (!empty($dolibarr_main_db_encrypted_pass)) {
448 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=disable_encryptdbpassconf&token='.newToken().'">'.$langs->trans("Disable").'</a>';
449 }
450}
451print "</td>";
452
453print "</td>";
454print '</tr>';
455
456
457// Disable link "Forget password" on logon
458
459print '<tr class="oddeven">';
460print '<td colspan="3">'.$langs->trans("DisableForgetPasswordLinkOnLogonPage").'</td>';
461print '<td class="center" width="60">';
462if (getDolGlobalString('MAIN_SECURITY_DISABLEFORGETPASSLINK')) {
463 print img_picto($langs->trans("Active"), 'tick');
464}
465print '</td>';
466if (!getDolGlobalString('MAIN_SECURITY_DISABLEFORGETPASSLINK')) {
467 print '<td class="center" width="100">';
468 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_MAIN_SECURITY_DISABLEFORGETPASSLINK&token='.newToken().'">'.$langs->trans("Activate").'</a>';
469 print "</td>";
470}
471if (getDolGlobalString('MAIN_SECURITY_DISABLEFORGETPASSLINK')) {
472 print '<td center="center" width="100">';
473 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=disable_MAIN_SECURITY_DISABLEFORGETPASSLINK&token='.newToken().'">'.$langs->trans("Disable").'</a>';
474 print "</td>";
475}
476print "</td>";
477print '</tr>';
478
479
480print '</table>';
481
482print '</form>';
483
484print '<br>';
485
486if (GETPOSTINT('info') > 0) {
487 if (function_exists('password_hash')) {
488 print $langs->trans("Note: The function password_hash exists on your PHP")."<br>\n";
489 } else {
490 print $langs->trans("Note: The function password_hash does not exist on your PHP")."<br>\n";
491 }
492 print 'MAIN_SECURITY_HASH_ALGO = '.getDolGlobalString('MAIN_SECURITY_HASH_ALGO')."<br>\n";
493 print 'MAIN_SECURITY_SALT = '.getDolGlobalString('MAIN_SECURITY_SALT')."<br>\n";
494}
495
496print '</div>';
497
498// End of page
499llxFooter();
500$db->close();
security_prepare_head()
Prepare array with list of tabs.
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
dolibarr_del_const($db, $name, $entity=1)
Delete a constant.
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader()
Empty header.
Definition wrapper.php:55
llxFooter()
Empty footer.
Definition wrapper.php:69
Class to manage generation of HTML components Only common components must be here.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
Show tabs of a record.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
encodedecode_dbpassconf($level=0)
Encode or decode database password in config file.
dol_encode($chain, $key='1')
Encode a string with base 64 algorithm + specific delta change.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.