dolibarr 18.0.6
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 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26// Load Dolibarr environment
27require '../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
30
31$action = GETPOST('action', 'aZ09');
32
33// Load translation files required by the page
34$langs->loadLangs(array("users", "admin", "other"));
35
36if (!$user->admin) {
38}
39
40// Allow/Disallow change to clear passwords once passwords are crypted
41$allow_disable_encryption = true;
42
43
44/*
45 * Actions
46 */
47
48if ($action == 'setgeneraterule') {
49 if (!dolibarr_set_const($db, 'USER_PASSWORD_GENERATED', GETPOST("value", "alphanohtml"), 'chaine', 0, '', $conf->entity)) {
50 dol_print_error($db);
51 }
52}
53
54if ($action == 'activate_encrypt') {
55 $error = 0;
56
57 $db->begin();
58
59 // 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.
60 dolibarr_del_const($db, "DATABASE_PWD_ENCRYPTED", $conf->entity);
61 // We set entity=0 (all) because DATABASE_PWD_ENCRYPTED is a setup into conf file, so always shared for everybody
62 $entityforall = 0;
63 dolibarr_set_const($db, "DATABASE_PWD_ENCRYPTED", "1", 'chaine', 0, '', $entityforall);
64
65 $sql = "SELECT u.rowid, u.pass, u.pass_crypted";
66 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
67 $sql .= " WHERE u.pass IS NOT NULL AND LENGTH(u.pass) < 32"; // Not a MD5 value
68
69 $resql = $db->query($sql);
70 if ($resql) {
71 $numrows = $db->num_rows($resql);
72 $i = 0;
73 while ($i < $numrows) {
74 $obj = $db->fetch_object($resql);
75 if (dol_hash($obj->pass)) {
76 $sql = "UPDATE ".MAIN_DB_PREFIX."user";
77 $sql .= " SET pass_crypted = '".dol_hash($obj->pass)."', pass = NULL";
78 $sql .= " WHERE rowid=".((int) $obj->rowid);
79 //print $sql;
80
81 $resql2 = $db->query($sql);
82 if (!$resql2) {
83 dol_print_error($db);
84 $error++;
85 break;
86 }
87
88 $i++;
89 }
90 }
91 } else {
92 dol_print_error($db);
93 }
94
95 //print $error." ".$sql;
96 //exit;
97 if (!$error) {
98 $db->commit();
99 } else {
100 $db->rollback();
101 dol_print_error($db, '');
102 }
103} elseif ($action == 'disable_encrypt') {
104 //On n'autorise pas l'annulation de l'encryption car les mots de passe ne peuvent pas etre decodes
105 //Do not allow "disable encryption" as passwords cannot be decrypted
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);
147
148 $patternInError = false;
149 if ($explodePattern[0] < 1 || $explodePattern[4] < 0) {
150 $patternInError = true;
151 }
152
153 if ($explodePattern[0] < $explodePattern[1] + $explodePattern[2] + $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);
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;
200if (is_resource($handle)) {
201 while (($file = readdir($handle)) !== false) {
202 if (preg_match('/(modGeneratePass[a-z]+)\.class\.php$/i', $file, $reg)) {
203 // Charging the numbering class
204 $classname = $reg[1];
205 require_once $dir.'/'.$file;
206
207 $obj = new $classname($db, $conf, $langs, $user);
208 $arrayhandler[$obj->id] = $obj;
209 $i++;
210 }
211 }
212 closedir($handle);
213}
214asort($arrayhandler);
215
216print '<div class="div-table-responsive-no-min">';
217print '<table class="noborder centpercent">';
218print '<tr class="liste_titre">';
219print '<td colspan="2">'.$langs->trans("RuleForGeneratedPasswords").'</td>';
220print '<td>'.$langs->trans("Example").'</td>';
221print '<td class="center">'.$langs->trans("Activated").'</td>';
222print '</tr>';
223
224$tabConf = explode(";", getDolGlobalString('USER_PASSWORD_PATTERN'));
225
226foreach ($arrayhandler as $key => $module) {
227 // Show modules according to features level
228 if (!empty($module->version) && $module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) {
229 continue;
230 }
231 if (!empty($module->version) && $module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) {
232 continue;
233 }
234
235 if ($module->isEnabled()) {
236 print '<tr class="oddeven"><td>';
237 print img_picto('', $module->picto, 'class="width25 size15x"').' ';
238 print ucfirst($key);
239 print "</td><td>\n";
240 print $module->getDescription().'<br>';
241 print $langs->trans("MinLength").': <span class="opacitymedium">'.$module->length.'</span>';
242 print '</td>';
243
244 // Show example of numbering module
245 print '<td class="nowraponall">';
246 $tmp = $module->getExample();
247 if (preg_match('/^Error/', $tmp)) {
248 $langs->load("errors");
249 print '<div class="error">'.$langs->trans($tmp).'</div>';
250 } elseif ($tmp == 'NotConfigured') {
251 print '<span class="opacitymedium">'.$langs->trans($tmp).'</span>';
252 } else {
253 print '<span class="opacitymedium">'.$tmp.'</span>';
254 }
255 print '</td>'."\n";
256
257 print '<td class="center">';
258 if ($conf->global->USER_PASSWORD_GENERATED == $key) {
259 //print img_picto('', 'tick');
260 print img_picto($langs->trans("Enabled"), 'switch_on');
261 } else {
262 print '<a href="'.$_SERVER['PHP_SELF'].'?action=setgeneraterule&token='.newToken().'&value='.$key.'">';
263 //print $langs->trans("Activate");
264 print img_picto($langs->trans("Disabled"), 'switch_off');
265 print '</a>';
266 }
267 print "</td></tr>\n";
268 }
269}
270print '</table>';
271print '</div>';
272
273print '</form>';
274
275
276// Pattern for Password Perso
277if ($conf->global->USER_PASSWORD_GENERATED == "Perso") {
278 print '<br>';
279
280 print '<div class="div-table-responsive-no-min">';
281 print '<table class="noborder centpercent">';
282 print '<tr class="liste_titre">';
283 print '<td colspan="2"> '.$langs->trans("PasswordPatternDesc").'</td>';
284 print '</tr>';
285
286
287 print '<tr class="oddeven">';
288 print '<td>'.$langs->trans("MinLength")."</td>";
289 print '<td><input type="number" value="'.$tabConf[0].'" id="minlenght" min="1"></td>';
290 print '</tr>';
291
292
293 print '<tr class="oddeven">';
294 print '<td>'.$langs->trans("NbMajMin")."</td>";
295 print '<td><input type="number" value="'.$tabConf[1].'" id="NbMajMin" min="0"></td>';
296 print '</tr>';
297
298
299 print '<tr class="oddeven">';
300 print '<td>'.$langs->trans("NbNumMin")."</td>";
301 print '<td><input type="number" value="'.$tabConf[2].'" id="NbNumMin" min="0"></td>';
302 print '</tr>';
303
304
305 print '<tr class="oddeven">';
306 print '<td>'.$langs->trans("NbSpeMin")."</td>";
307 print '<td><input type="number" value="'.$tabConf[3].'" id="NbSpeMin" min="0"></td>';
308 print '</tr>';
309
310
311 print '<tr class="oddeven">';
312 print '<td>'.$langs->trans("NbIteConsecutive")."</td>";
313 print '<td><input type="number" value="'.$tabConf[4].'" id="NbIteConsecutive" min="0"></td>';
314 print '</tr>';
315
316
317 print '<tr class="oddeven">';
318 print '<td>'.$langs->trans("NoAmbiCaracAutoGeneration")."</td>";
319 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>';
320 print '</tr>';
321
322 print '</table>';
323
324 print '<div class="center">';
325 print '<a class="button button-save" id="linkChangePattern">'.$langs->trans("Save").'</a>';
326 print '</div>';
327
328 print '<br><br>';
329
330 print '<script type="text/javascript">';
331 print ' function getStringArg(){';
332 print ' var pattern = "";';
333 print ' pattern += $("#minlenght").val() + ";";';
334 print ' pattern += $("#NbMajMin").val() + ";";';
335 print ' pattern += $("#NbNumMin").val() + ";";';
336 print ' pattern += $("#NbSpeMin").val() + ";";';
337 print ' pattern += $("#NbIteConsecutive").val() + ";";';
338 print ' pattern += $("#NoAmbiCaracAutoGeneration")[0].checked ? "1" : "0";';
339 print ' return pattern;';
340 print ' }';
341
342 print ' function valuePossible(){';
343 print ' var fields = ["#minlenght", "#NbMajMin", "#NbNumMin", "#NbSpeMin", "#NbIteConsecutive"];';
344 print ' for(var i = 0 ; i < fields.length ; i++){';
345 print ' if($(fields[i]).val() < $(fields[i]).attr("min")){';
346 print ' return false;';
347 print ' }';
348 print ' }';
349 print ' ';
350 print ' var length = parseInt($("#minlenght").val());';
351 print ' var length_mini = parseInt($("#NbMajMin").val()) + parseInt($("#NbNumMin").val()) + parseInt($("#NbSpeMin").val());';
352 print ' return length >= length_mini;';
353 print ' }';
354
355 print ' function generatelink(){';
356 print ' return "security.php?action=updatepattern&token='.newToken().'&pattern="+getStringArg();';
357 print ' }';
358
359 print ' function valuePatternChange(){';
360 print ' console.log("valuePatternChange");';
361 print ' var lang_save = "'.$langs->trans("Save").'";';
362 print ' var lang_error = "'.$langs->trans("Error").'";';
363 print ' var lang_Disabled = "'.$langs->trans("Disabled").'";';
364 print ' var lang_Activated = "'.$langs->trans("Activated").'";';
365 print ' $("#textcheckbox").html($("#NoAmbiCaracAutoGeneration")[0].checked ? unescape(lang_Activated) : unescape(lang_Disabled));';
366 print ' if(valuePossible()){';
367 print ' $("#linkChangePattern").attr("href",generatelink()).text(lang_save);';
368 print ' }';
369 print ' else{';
370 print ' $("#linkChangePattern").attr("href", null).text(lang_error);';
371 print ' }';
372 print ' }';
373
374 print ' $("#minlenght").change(function(){valuePatternChange();});';
375 print ' $("#NbMajMin").change(function(){valuePatternChange();});';
376 print ' $("#NbNumMin").change(function(){valuePatternChange();});';
377 print ' $("#NbSpeMin").change(function(){valuePatternChange();});';
378 print ' $("#NbIteConsecutive").change(function(){valuePatternChange();});';
379 print ' $("#NoAmbiCaracAutoGeneration").change(function(){valuePatternChange();});';
380
381 print '</script>';
382}
383
384
385// Crypt passwords in database
386
387print '<br>';
388print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
389print '<input type="hidden" name="token" value="'.newToken().'">';
390print '<input type="hidden" name="action" value="encrypt">';
391
392print '<table class="noborder centpercent">';
393print '<tr class="liste_titre">';
394print '<td colspan="3">'.$langs->trans("Parameters").'</td>';
395print '<td class="center">'.$langs->trans("Activated").'</td>';
396print '<td class="center"></td>';
397print '</tr>';
398
399// Disable clear password in database
400print '<tr class="oddeven">';
401print '<td colspan="3">'.$langs->trans("DoNotStoreClearPassword").'</td>';
402print '<td class="center" width="60">';
403if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
404 print img_picto($langs->trans("Active"), 'tick');
405}
406print '</td>';
407if (!getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
408 print '<td class="center" width="100">';
409 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?action=activate_encrypt&token='.newToken().'">'.$langs->trans("Activate").'</a>';
410 print "</td>";
411}
412
413// Database conf file encryption
414if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
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 '-';
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 (GETPOST('info', 'int') > 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 exists 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()
Empty header.
Definition wrapper.php:56
llxFooter()
Empty footer.
Definition wrapper.php:70
Class to manage generation of HTML components Only common components must be here.
load_fiche_titre($titre, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
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.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
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.
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')
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.