dolibarr 21.0.0-alpha
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// Load array with all password generation modules
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 $reg = array();
204 if (preg_match('/(modGeneratePass[a-z]+)\.class\.php$/i', $file, $reg)) {
205 // Charging the numbering class
206 $classname = $reg[1];
207 require_once $dir.'/'.$file;
208
209 $obj = new $classname($db, $conf, $langs, $user);
210 '@phan-var-force ModeleGenPassword $obj';
211 $arrayhandler[$obj->id] = $obj;
212 $i++;
213 }
214 }
215 closedir($handle);
216}
217asort($arrayhandler);
218
219print '<div class="div-table-responsive-no-min">';
220print '<table class="noborder centpercent">';
221print '<tr class="liste_titre">';
222print '<td colspan="2">'.$langs->trans("RuleForGeneratedPasswords").'</td>';
223print '<td>'.$langs->trans("Example").'</td>';
224print '<td class="center">'.$langs->trans("Activated").'</td>';
225print '</tr>';
226
227$tabConf = explode(";", getDolGlobalString('USER_PASSWORD_PATTERN'));
228
229foreach ($arrayhandler as $key => $module) {
230 // Show modules according to features level
231 if (!empty($module->version) && $module->version == 'development' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
232 continue;
233 }
234 if (!empty($module->version) && $module->version == 'experimental' && getDolGlobalInt('MAIN_FEATURES_LEVEL') < 1) {
235 continue;
236 }
237
238 if ($module->isEnabled()) {
239 print '<tr class="oddeven"><td>';
240 print img_picto('', $module->picto, 'class="width25 size15x marginrightonly"').' ';
241 print ucfirst($key);
242 print "</td><td>\n";
243 print $module->getDescription().'<br>';
244 print $langs->trans("MinLength").': <span class="opacitymedium">'.$module->length.'</span>';
245 print '</td>';
246
247 // Show example of numbering module
248 print '<td class="nowraponall">';
249 $tmp = $module->getExample();
250 if (preg_match('/^Error/', $tmp)) {
251 $langs->load("errors");
252 print '<div class="error">'.$langs->trans($tmp).'</div>';
253 } elseif ($tmp == 'NotConfigured') {
254 print '<span class="opacitymedium">'.$langs->trans($tmp).'</span>';
255 } else {
256 print '<span class="opacitymedium">'.$tmp.'</span>';
257 }
258 print '</td>'."\n";
259
260 print '<td class="center">';
261 if ($conf->global->USER_PASSWORD_GENERATED == $key) {
262 //print img_picto('', 'tick');
263 print img_picto($langs->trans("Enabled"), 'switch_on');
264 } else {
265 print '<a href="'.$_SERVER['PHP_SELF'].'?action=setgeneraterule&token='.newToken().'&value='.$key.'">';
266 //print $langs->trans("Activate");
267 print img_picto($langs->trans("Disabled"), 'switch_off');
268 print '</a>';
269 }
270 print "</td></tr>\n";
271 }
272}
273print '</table>';
274print '</div>';
275
276print '</form>';
277
278
279// Pattern for Password Perso
280if (getDolGlobalString('USER_PASSWORD_GENERATED') == "Perso") {
281 print '<br>';
282
283 print '<div class="div-table-responsive-no-min">';
284 print '<table class="noborder centpercent">';
285 print '<tr class="liste_titre">';
286 print '<td colspan="2"> '.$langs->trans("PasswordPatternDesc").'</td>';
287 print '</tr>';
288
289
290 print '<tr class="oddeven">';
291 print '<td>'.$langs->trans("MinLength")."</td>";
292 print '<td><input type="number" class="width50 right" value="'.$tabConf[0].'" id="minlength" min="1"></td>';
293 print '</tr>';
294
295
296 print '<tr class="oddeven">';
297 print '<td>'.$langs->trans("NbMajMin")."</td>";
298 print '<td><input type="number" class="width50 right" value="'.$tabConf[1].'" id="NbMajMin" min="0"></td>';
299 print '</tr>';
300
301
302 print '<tr class="oddeven">';
303 print '<td>'.$langs->trans("NbNumMin")."</td>";
304 print '<td><input type="number" class="width50 right" value="'.$tabConf[2].'" id="NbNumMin" min="0"></td>';
305 print '</tr>';
306
307
308 print '<tr class="oddeven">';
309 print '<td>'.$langs->trans("NbSpeMin")."</td>";
310 print '<td><input type="number" class="width50 right" value="'.$tabConf[3].'" id="NbSpeMin" min="0"></td>';
311 print '</tr>';
312
313
314 print '<tr class="oddeven">';
315 print '<td>'.$langs->trans("NbIteConsecutive")."</td>";
316 print '<td><input type="number" class="width50 right" value="'.$tabConf[4].'" id="NbIteConsecutive" min="0"></td>';
317 print '</tr>';
318
319
320 print '<tr class="oddeven">';
321 print '<td>'.$langs->trans("NoAmbiCaracAutoGeneration")."</td>";
322 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>';
323 print '</tr>';
324
325 print '</table>';
326
327 print '<div class="center">';
328 print '<a class="button button-save" id="linkChangePattern">'.$langs->trans("Save").'</a>';
329 print '</div>';
330
331 print '<br><br>';
332
333 print '<script type="text/javascript">';
334 print ' function getStringArg(){';
335 print ' var pattern = "";';
336 print ' pattern += $("#minlenght").val() + ";";';
337 print ' pattern += $("#NbMajMin").val() + ";";';
338 print ' pattern += $("#NbNumMin").val() + ";";';
339 print ' pattern += $("#NbSpeMin").val() + ";";';
340 print ' pattern += $("#NbIteConsecutive").val() + ";";';
341 print ' pattern += $("#NoAmbiCaracAutoGeneration")[0].checked ? "1" : "0";';
342 print ' return pattern;';
343 print ' }';
344
345 print ' function valuePossible(){';
346 print ' var fields = ["#minlenght", "#NbMajMin", "#NbNumMin", "#NbSpeMin", "#NbIteConsecutive"];';
347 print ' for(var i = 0 ; i < fields.length ; i++){';
348 print ' if($(fields[i]).val() < $(fields[i]).attr("min")){';
349 print ' return false;';
350 print ' }';
351 print ' }';
352 print ' ';
353 print ' var length = parseInt($("#minlenght").val());';
354 print ' var length_mini = parseInt($("#NbMajMin").val()) + parseInt($("#NbNumMin").val()) + parseInt($("#NbSpeMin").val());';
355 print ' return length >= length_mini;';
356 print ' }';
357
358 print ' function generatelink(){';
359 print ' return "security.php?action=updatepattern&token='.newToken().'&pattern="+getStringArg();';
360 print ' }';
361
362 print ' function valuePatternChange(){';
363 print ' console.log("valuePatternChange");';
364 print ' var lang_save = "'.$langs->trans("Save").'";';
365 print ' var lang_error = "'.$langs->trans("Error").'";';
366 print ' var lang_Disabled = "'.$langs->trans("Disabled").'";';
367 print ' var lang_Activated = "'.$langs->trans("Activated").'";';
368 print ' $("#textcheckbox").html($("#NoAmbiCaracAutoGeneration")[0].checked ? unescape(lang_Activated) : unescape(lang_Disabled));';
369 print ' if(valuePossible()){';
370 print ' $("#linkChangePattern").attr("href",generatelink()).text(lang_save);';
371 print ' }';
372 print ' else{';
373 print ' $("#linkChangePattern").attr("href", null).text(lang_error);';
374 print ' }';
375 print ' }';
376
377 print ' $("#minlenght").change(function(){valuePatternChange();});';
378 print ' $("#NbMajMin").change(function(){valuePatternChange();});';
379 print ' $("#NbNumMin").change(function(){valuePatternChange();});';
380 print ' $("#NbSpeMin").change(function(){valuePatternChange();});';
381 print ' $("#NbIteConsecutive").change(function(){valuePatternChange();});';
382 print ' $("#NoAmbiCaracAutoGeneration").change(function(){valuePatternChange();});';
383
384 print '</script>';
385}
386
387
388// Crypt passwords in database
389
390print '<br>';
391print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
392print '<input type="hidden" name="token" value="'.newToken().'">';
393print '<input type="hidden" name="action" value="encrypt">';
394
395print '<table class="noborder centpercent">';
396print '<tr class="liste_titre">';
397print '<td colspan="3">'.$langs->trans("Parameters").'</td>';
398print '<td class="center">'.$langs->trans("Activated").'</td>';
399print '<td class="center"></td>';
400print '</tr>';
401
402// Disable clear password in database
403print '<tr class="oddeven">';
404print '<td colspan="3">'.$langs->trans("DoNotStoreClearPassword").'</td>';
405print '<td class="center" width="60">';
406if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
407 print img_picto($langs->trans("Active"), 'tick');
408}
409print '</td>';
410if (!getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
411 print '<td class="center" width="100">';
412 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_encrypt&token='.newToken().'">'.$langs->trans("Activate").'</a>';
413 print "</td>";
414} else {
415 print '<td class="center" width="100">';
416 if ($allow_disable_encryption) {
417 //On n'autorise pas l'annulation de l'encryption car les mots de passe ne peuvent pas etre decodes
418 //Do not allow "disable encryption" as passwords cannot be decrypted
419 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=disable_encrypt&token='.newToken().'">'.$langs->trans("Disable").'</a>';
420 } else {
421 print '<span class="opacitymedium">'.$langs->trans("Always").'</span>';
422 }
423 print "</td>";
424}
425print "</td>";
426print '</tr>';
427
428
429// Crypt password into config file conf.php
430
431print '<tr class="oddeven">';
432print '<td colspan="3">'.$langs->trans("MainDbPasswordFileConfEncrypted").'</td>';
433print '<td align="center" width="60">';
434if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) {
435 print img_picto($langs->trans("Active"), 'tick');
436}
437
438print '</td>';
439
440print '<td class="center" width="100">';
441if (empty($dolibarr_main_db_pass) && empty($dolibarr_main_db_encrypted_pass)) {
442 $langs->load("errors");
443 print img_warning($langs->trans("WarningPassIsEmpty"));
444} else {
445 if (empty($dolibarr_main_db_encrypted_pass)) {
446 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_encryptdbpassconf&token='.newToken().'">'.$langs->trans("Activate").'</a>';
447 }
448 if (!empty($dolibarr_main_db_encrypted_pass)) {
449 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=disable_encryptdbpassconf&token='.newToken().'">'.$langs->trans("Disable").'</a>';
450 }
451}
452print "</td>";
453
454print "</td>";
455print '</tr>';
456
457
458// Disable link "Forget password" on logon
459
460print '<tr class="oddeven">';
461print '<td colspan="3">'.$langs->trans("DisableForgetPasswordLinkOnLogonPage").'</td>';
462print '<td class="center" width="60">';
463if (getDolGlobalString('MAIN_SECURITY_DISABLEFORGETPASSLINK')) {
464 print img_picto($langs->trans("Active"), 'tick');
465}
466print '</td>';
467if (!getDolGlobalString('MAIN_SECURITY_DISABLEFORGETPASSLINK')) {
468 print '<td class="center" width="100">';
469 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_MAIN_SECURITY_DISABLEFORGETPASSLINK&token='.newToken().'">'.$langs->trans("Activate").'</a>';
470 print "</td>";
471}
472if (getDolGlobalString('MAIN_SECURITY_DISABLEFORGETPASSLINK')) {
473 print '<td center="center" width="100">';
474 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=disable_MAIN_SECURITY_DISABLEFORGETPASSLINK&token='.newToken().'">'.$langs->trans("Disable").'</a>';
475 print "</td>";
476}
477print "</td>";
478print '</tr>';
479
480
481print '</table>';
482
483print '</form>';
484
485print '<br>';
486
487if (GETPOSTINT('info') > 0) {
488 if (function_exists('password_hash')) {
489 print $langs->trans("Note: The function password_hash exists on your PHP")."<br>\n";
490 } else {
491 print $langs->trans("Note: The function password_hash does not exist on your PHP")."<br>\n";
492 }
493 print 'MAIN_SECURITY_HASH_ALGO = '.getDolGlobalString('MAIN_SECURITY_HASH_ALGO')."<br>\n";
494 print 'MAIN_SECURITY_SALT = '.getDolGlobalString('MAIN_SECURITY_SALT')."<br>\n";
495}
496
497print '</div>';
498
499// End of page
500llxFooter();
501$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($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:70
Class to manage generation of HTML components Only common components must be here.
llxFooter()
Footer empty.
Definition document.php:107
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.
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 a 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.