dolibarr 25.0.0-alpha
security2.lib.php File Reference

Set of function used for dolibarr security (not common functions). More...

Go to the source code of this file.

Functions

 dol_getwebuser ($mode)
 Return user/group account of web server.
 
 checkLoginPassEntity ($usertotest, $passwordtotest, $entitytotest, $authmode, $context='')
 Return a login if login/pass was successful.
 
if(!function_exists( 'dol_loginfunction')) makesalt ($type=CRYPT_SALT_LENGTH)
 Initialise the salt for the crypt function.
 
 encodedecode_dbpassconf ($level=0)
 Encode or decode database password in config file.
 
 isPasswordGenerationNoneForbidden ()
 Return if the 'none' password generation model (the one that applies no rule at all) is forbidden on this installation.
 
 getPasswordPatternMinLength ()
 Return the lowest value allowed for the minimum length (first field of USER_PASSWORD_PATTERN) of the 'Perso' password generation model.
 
 getRandomPassword ($generic=false, $replaceambiguouschars=null, $length=32)
 Return a generated password using default module.
 
 dolJSToSetRandomPassword ($htmlname, $htmlnameofbutton='generate_token', $generic=1)
 Output javascript to autoset a generated password using default module into a HTML element.
 
 showEyeForField ($htmlname, $htmlnameofinput)
 Output the eye picto to show/hide a password HTML field.
 
 dolTotpNewSecret ($nbbytes=20)
 Generate a new secret for a TOTP enrollment (RFC 6238), in the base32 form expected by the authenticator applications.
 
 dolTotpBase32Encode ($bin)
 Encode a binary string into base32 (alphabet of the RFC 4648, no padding).
 
 dolTotpBase32Decode ($base32)
 Decode a base32 string (alphabet of the RFC 4648).
 
 dolTotpGetCode ($base32secret, $timestep, $digits=6, $algo='sha1')
 Compute the TOTP code (RFC 6238) of a secret for one time step.
 
 dolTotpCheckCode ($base32secret, $code, $timestamp=0, $period=30, $digits=6, $drift=1)
 Check a code sent by a user against a secret, accepting a drift of some periods to tolerate a clock offset.
 
 dolTotpGetUri ($login, $base32secret, $issuer='', $digits=6, $period=30)
 Build the otpauth:// URI of an enrollment, to be shown as a QR code to the user.
 
 dolTotpGetEnrollment ($db, $fk_user)
 Load the TOTP enrollment of a user.
 
 dolTotpSaveEnrollment ($db, $fk_user, $secret, $laststep, $entity=1)
 Save a TOTP enrollment confirmed by a valid code.
 
 dolTotpSetLastStep ($db, $rowid, $laststep)
 Store the time step of the last code accepted, so the same code can't be played twice.
 
 dolTotpFormatStep ($timestep)
 Format a time step for the 'state' field, at a fixed width so the string comparison done in SQL is a numeric one.
 
 dolTotpDeleteEnrollment ($db, $fk_user)
 Delete the TOTP enrollment of a user, who then logs in with the password only again.
 
 dolTotpStartSecondFactor ($db, $login, $entity)
 Start the second step of a two-factor authentication, just after a password has been validated.
 
 dolTotpCheckPendingLogin ($db)
 Check the code of the second step of a two-factor authentication.
 
 dolTotpGetNbFailedAuthFromIp ($db)
 Count the failed authentications recorded for the IP of the current request over the last 24 hours.
 

Detailed Description

Set of function used for dolibarr security (not common functions).

Warning, this file must not depends on other library files, except function.lib.php because it is used at low code level.

Definition in file security2.lib.php.

Function Documentation

◆ checkLoginPassEntity()

checkLoginPassEntity ( $usertotest,
$passwordtotest,
$entitytotest,
$authmode,
$context = '' )

Return a login if login/pass was successful.

Parameters
string$usertotestLogin value to test
string$passwordtotestPassword value to test
int | string$entitytotestInstance of data we must check
string[]$authmodeArray list of selected authentication mode array('http', 'dolibarr', 'xxx'...)
'api'|'dav'|'ws'|''$context Context checkLoginPassEntity was created for ('api', 'dav', 'ws', '')
Returns
string Login or '' or '–bad-login-validity–'

Show Dolibarr default login page. Part of this code is also duplicated into main.inc.php\top_htmlhead

Parameters
Translate$langsLang object (must be initialized by a new).
Conf$confConf object
Societe$mysocCompany object
Returns
void

Definition at line 59 of file security2.lib.php.

References $conf, $context, dol_buildpath(), dol_osencode(), and dol_syslog().

Referenced by check_authentication(), and Login\index().

◆ dol_getwebuser()

dol_getwebuser ( $mode)

Return user/group account of web server.

Parameters
string$mode'user' or 'group'
Returns
string Return user or group of web server

Definition at line 37 of file security2.lib.php.

◆ dolJSToSetRandomPassword()

dolJSToSetRandomPassword ( $htmlname,
$htmlnameofbutton = 'generate_token',
$generic = 1 )

Output javascript to autoset a generated password using default module into a HTML element.

Parameters
string$htmlnameHTML name of element to insert key into
string$htmlnameofbuttonHTML name of button
int$generic1=Return a generic pass, 0=Return a pass following setup rules
Returns
string HTML javascript code to set a password
See also
getRandomPassword()

Definition at line 612 of file security2.lib.php.

References $conf, and dol_escape_js().

Referenced by FormSetupItem\generateInputFieldSecureKey().

◆ dolTotpBase32Decode()

dolTotpBase32Decode ( $base32)

Decode a base32 string (alphabet of the RFC 4648).

The chars out of the alphabet, like the spaces of a key typed by hand, are ignored.

Parameters
string$base32Base32 string
Returns
string Binary string

Definition at line 716 of file security2.lib.php.

References dol_strlen(), and dol_strtoupper().

Referenced by dolTotpGetCode().

◆ dolTotpBase32Encode()

dolTotpBase32Encode ( $bin)

Encode a binary string into base32 (alphabet of the RFC 4648, no padding).

Parameters
string$binBinary string
Returns
string Base32 string

Definition at line 695 of file security2.lib.php.

Referenced by dolTotpNewSecret().

◆ dolTotpCheckCode()

dolTotpCheckCode ( $base32secret,
$code,
$timestamp = 0,
$period = 30,
$digits = 6,
$drift = 1 )

Check a code sent by a user against a secret, accepting a drift of some periods to tolerate a clock offset.

Parameters
string$base32secretSecret in base32
string$codeCode sent by the user
int$timestampTimestamp to check at (0 = now)
int$periodDuration of a time step, in seconds
int$digitsNumber of digits of the code
int$driftNumber of periods accepted before and after the current one
Returns
int Accepted time step, to be stored to refuse a replay of the same code, or 0 if no step matches
See also
dolTotpNewSecret()

Definition at line 763 of file security2.lib.php.

References dol_now(), dol_strlen(), and dolTotpGetCode().

Referenced by dolTotpCheckPendingLogin().

◆ dolTotpCheckPendingLogin()

dolTotpCheckPendingLogin ( $db)

Check the code of the second step of a two-factor authentication.

The login is read from the session and never from the request, so the first step can't be skipped by posting a code alone.

Parameters
DoliDB$dbDatabase handler
Returns
string The login if the code is valid, '' otherwise
See also
dolTotpStartSecondFactor()

Definition at line 982 of file security2.lib.php.

References $conf, dol_now(), dol_syslog(), dolTotpCheckCode(), dolTotpGetEnrollment(), dolTotpGetNbFailedAuthFromIp(), dolTotpSetLastStep(), getDolGlobalInt(), GETPOST(), and getUserRemoteIP().

◆ dolTotpDeleteEnrollment()

dolTotpDeleteEnrollment ( $db,
$fk_user )

Delete the TOTP enrollment of a user, who then logs in with the password only again.

Parameters
DoliDB$dbDatabase handler
int$fk_userId of the user
Returns
int 1 if OK, -1 if KO

Definition at line 922 of file security2.lib.php.

References dol_syslog().

◆ dolTotpFormatStep()

dolTotpFormatStep ( $timestep)

Format a time step for the 'state' field, at a fixed width so the string comparison done in SQL is a numeric one.

Parameters
int$timestepTime step
Returns
string Time step left padded with zeros

Definition at line 910 of file security2.lib.php.

Referenced by dolTotpSaveEnrollment(), and dolTotpSetLastStep().

◆ dolTotpGetCode()

dolTotpGetCode ( $base32secret,
$timestep,
$digits = 6,
$algo = 'sha1' )

Compute the TOTP code (RFC 6238) of a secret for one time step.

Parameters
string$base32secretSecret in base32
int$timestepTime step, that is the timestamp divided by the period
int$digitsNumber of digits of the code
string$algoHash algorithm ('sha1', 'sha256' or 'sha512')
Returns
string Code, left padded with zeros

Definition at line 743 of file security2.lib.php.

References dolTotpBase32Decode().

Referenced by dolTotpCheckCode().

◆ dolTotpGetEnrollment()

dolTotpGetEnrollment ( $db,
$fk_user )

Load the TOTP enrollment of a user.

The row is written into llx_oauth_token only once the enrollment has been confirmed by a valid code, so its presence means the 2FA is active for this user.

Parameters
DoliDB$dbDatabase handler
int$fk_userId of the user
Returns
array{rowid:int,secret:string,laststep:int,datec:int|string,lastaccess:int|string}|int|null Enrollment, null if the user has no 2FA, -1 if the query failed or the row can't be read: a caller must then refuse the login, not treat it as no 2FA
See also
dolTotpSaveEnrollment(), dolTotpDeleteEnrollment()

Definition at line 815 of file security2.lib.php.

References dol_syslog(), and dolDecrypt().

Referenced by check_authentication(), dolTotpCheckPendingLogin(), dolTotpStartSecondFactor(), and Login\index().

◆ dolTotpGetNbFailedAuthFromIp()

dolTotpGetNbFailedAuthFromIp ( $db)

Count the failed authentications recorded for the IP of the current request over the last 24 hours.

This is the count check_user_password_dolibarr() does before testing a password; it needs MAIN_LOGEVENTS_USER_LOGIN_FAILED to be enabled, like it.

Parameters
DoliDB$dbDatabase handler
Returns
int Number of USER_LOGIN_FAILED events, or -1 if they can't be counted

Definition at line 1050 of file security2.lib.php.

References dol_now(), dol_syslog(), and getUserRemoteIP().

Referenced by dolTotpCheckPendingLogin().

◆ dolTotpGetUri()

dolTotpGetUri ( $login,
$base32secret,
$issuer = '',
$digits = 6,
$period = 30 )

Build the otpauth:// URI of an enrollment, to be shown as a QR code to the user.

Parameters
string$loginLogin of the user, shown as the account name in the application
string$base32secretSecret in base32
string$issuerName of the issuer shown in the application ('' = name of the company)
int$digitsNumber of digits of the code
int$periodDuration of a time step, in seconds
Returns
string URI otpauth://totp/...

Definition at line 794 of file security2.lib.php.

References $mysoc.

◆ dolTotpNewSecret()

dolTotpNewSecret ( $nbbytes = 20)

Generate a new secret for a TOTP enrollment (RFC 6238), in the base32 form expected by the authenticator applications.

Parameters
int$nbbytesLength of the secret in bytes (20 = 160 bits, the recommendation of the RFC 4226)
Returns
string Secret in base32
See also
dolTotpCheckCode(), dolTotpGetUri()

Definition at line 684 of file security2.lib.php.

References dolTotpBase32Encode().

◆ dolTotpSaveEnrollment()

dolTotpSaveEnrollment ( $db,
$fk_user,
$secret,
$laststep,
$entity = 1 )

Save a TOTP enrollment confirmed by a valid code.

The secret is encrypted at rest and written only once, the accepted time step goes into the 'state' field.

Parameters
DoliDB$dbDatabase handler
int$fk_userId of the user
string$secretSecret in base32
int$laststepTime step of the code that confirmed the enrollment
int$entityEntity of the user
Returns
int 1 if OK, -1 if KO, -2 if the secret can't be encrypted (no instance key or no openssl)

Definition at line 855 of file security2.lib.php.

References dol_now(), dol_syslog(), dolEncrypt(), and dolTotpFormatStep().

◆ dolTotpSetLastStep()

dolTotpSetLastStep ( $db,
$rowid,
$laststep )

Store the time step of the last code accepted, so the same code can't be played twice.

The update is conditional: when two requests carry the same code at the same time, only the first one gets its row updated and the second one is refused.

Parameters
DoliDB$dbDatabase handler
int$rowidId of the row of the enrollment
int$laststepTime step just accepted
Returns
int 1 if OK, 0 if a code of this step or later was already accepted, -1 if KO

Definition at line 885 of file security2.lib.php.

References dol_now(), dol_syslog(), and dolTotpFormatStep().

Referenced by dolTotpCheckPendingLogin().

◆ dolTotpStartSecondFactor()

dolTotpStartSecondFactor ( $db,
$login,
$entity )

Start the second step of a two-factor authentication, just after a password has been validated.

The session is not opened here: we only remember that the first step succeeded, so a code can be asked for in the next request.

Parameters
DoliDB$dbDatabase handler
string$loginLogin validated by the first step
int$entityEntity the login was tested on
Returns
string The login if this user has no 2FA, or '' to ask for a code first
See also
dolTotpCheckPendingLogin()

Definition at line 944 of file security2.lib.php.

References $conf, dol_now(), dol_syslog(), and dolTotpGetEnrollment().

◆ encodedecode_dbpassconf()

encodedecode_dbpassconf ( $level = 0)

Encode or decode database password in config file.

Parameters
int$levelEncode level: 0 no encoding, 1 encoding
Returns
int Return integer <0 if KO, >0 if OK

Definition at line 372 of file security2.lib.php.

References conf(), dol_decode(), dol_syslog(), dolDecrypt(), and dolEncrypt().

◆ getPasswordPatternMinLength()

getPasswordPatternMinLength ( )

Return the lowest value allowed for the minimum length (first field of USER_PASSWORD_PATTERN) of the 'Perso' password generation model.

When the 'none' model is forbidden on this installation (see isPasswordGenerationNoneForbidden()), the Perso model must not be tuned down to a weak value either, so a floor of 10 characters is enforced in the admin screen, when saving the pattern, and at generation/validation time.

Returns
int Minimum allowed value for the Perso model minimum length

Definition at line 497 of file security2.lib.php.

References isPasswordGenerationNoneForbidden().

Referenced by modGeneratePassPerso\__construct().

◆ getRandomPassword()

getRandomPassword ( $generic = false,
$replaceambiguouschars = null,
$length = 32 )

Return a generated password using default module.

Parameters
bool$generictrue=Create a generic key (32 chars/numbers), false=Create a password using the configured password generation module.
?array<string>$replaceambiguouschars Discard ambiguous characters. For example: array('I').
int$lengthLength of random string (Used only if $generic is true)
Returns
string New value for password
See also
dol_hash(), dolJSToSetRandomPassword() @phan-suppress DolibarrForbiddenFunctionPlugin

Definition at line 512 of file security2.lib.php.

References $conf, dol_syslog(), getDolGlobalString(), and ModeleGenPassword\loadAndInstantiate().

Referenced by modEventOrganization\__construct(), modPropale\__construct(), addFileIntoDatabaseIndex(), ActionsAdherentCardCommon\assign_values(), ActionsContactCardCommon\assign_values(), CommonObject\getLastMainDocLink(), CommonObject\indexFile(), openid_connect_create_user(), Documents\post(), Adherent\setPassword(), and User\setPassword().

◆ isPasswordGenerationNoneForbidden()

isPasswordGenerationNoneForbidden ( )

Return if the 'none' password generation model (the one that applies no rule at all) is forbidden on this installation.

It is locked by the conf.php variable $dolibarr_main_restrict_password_generation_none (exposed as $conf->file->restrict_password_generation_none), which can only be changed by editing the config file on the server. When forbidden, the model is hidden from the admin screen, cannot be selected, and any value already set to 'none' falls back to the 'standard' model at generation/validation time.

Returns
int 1 if the 'none' model must not be used, 0 otherwise

Definition at line 481 of file security2.lib.php.

References $conf.

Referenced by getPasswordPatternMinLength(), modGeneratePassNone\isEnabled(), and ModeleGenPassword\loadAndInstantiate().

◆ makesalt()

if(!function_exists('dol_loginfunction')) makesalt ( $type = CRYPT_SALT_LENGTH)

Initialise the salt for the crypt function.

Parameters
int$type2 =>Return a salt for DES encryption 12=>Return a salt for MD5 encryption Undefined=>Return a salt for default encryption
Returns
string Salt string

Definition at line 335 of file security2.lib.php.

References dol_strlen(), and dol_syslog().

Referenced by MailmanSpip\add_to_spip().

◆ showEyeForField()

showEyeForField ( $htmlname,
$htmlnameofinput )

Output the eye picto to show/hide a password HTML field.

Parameters
string$htmlnameHTML name of element to insert key into
string$htmlnameofinputHTML id of input field
Returns
string HTML javascript code to set a password

Definition at line 651 of file security2.lib.php.