Passed
Pull Request — master (#4682)
by Nils
06:23
created

identifyDoInitialChecks()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 121
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 79
nc 6
nop 6
dl 0
loc 121
rs 7.5248
c 2
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Teampass - a collaborative passwords manager.
7
 * ---
8
 * This file is part of the TeamPass project.
9
 * 
10
 * TeamPass is free software: you can redistribute it and/or modify it
11
 * under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation, version 3 of the License.
13
 * 
14
 * TeamPass is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU General Public License for more details.
18
 * 
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 * 
22
 * Certain components of this file may be under different licenses. For
23
 * details, see the `licenses` directory or individual file headers.
24
 * ---
25
 * @file      identify.php
26
 * @author    Nils Laumaillé ([email protected])
27
 * @copyright 2009-2025 Teampass.net
28
 * @license   GPL-3.0
29
 * @see       https://www.teampass.net
30
 */
31
32
use voku\helper\AntiXSS;
33
use TeampassClasses\SessionManager\SessionManager;
34
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
35
use TeampassClasses\Language\Language;
36
use TeampassClasses\PerformChecks\PerformChecks;
37
use TeampassClasses\ConfigManager\ConfigManager;
38
use TeampassClasses\NestedTree\NestedTree;
39
use TeampassClasses\PasswordManager\PasswordManager;
40
use Duo\DuoUniversal\Client;
41
use Duo\DuoUniversal\DuoException;
42
use RobThree\Auth\TwoFactorAuth;
43
use TeampassClasses\LdapExtra\LdapExtra;
44
use TeampassClasses\LdapExtra\OpenLdapExtra;
45
use TeampassClasses\LdapExtra\ActiveDirectoryExtra;
46
use TeampassClasses\OAuth2Controller\OAuth2Controller;
47
48
// Load functions
49
require_once 'main.functions.php';
50
51
// init
52
loadClasses('DB');
53
$session = SessionManager::getSession();
54
$request = SymfonyRequest::createFromGlobals();
55
$lang = new Language($session->get('user-language') ?? 'english');
56
57
// Load config
58
$configManager = new ConfigManager();
59
$SETTINGS = $configManager->getAllSettings();
60
61
// Define Timezone
62
date_default_timezone_set($SETTINGS['timezone'] ?? 'UTC');
63
64
// Set header properties
65
header('Content-type: text/html; charset=utf-8');
66
header('Cache-Control: no-cache, no-store, must-revalidate');
67
error_reporting(E_ERROR);
68
69
// --------------------------------- //
70
71
// Prepare POST variables
72
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
73
$post_login = filter_input(INPUT_POST, 'login', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
74
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES);
75
76
if ($post_type === 'identify_user') {
77
    //--------
78
    // NORMAL IDENTICATION STEP
79
    //--------
80
81
    // Ensure Complexity levels are translated
82
    defineComplexity();
83
84
    // Identify the user through Teampass process
85
    identifyUser($post_data, $SETTINGS);
86
87
    // ---
88
    // ---
89
    // ---
90
} elseif ($post_type === 'get2FAMethods') {
91
    //--------
92
    // Get MFA methods
93
    //--------
94
    //
95
96
    // Encrypt data to return
97
    echo json_encode([
98
        'ret' => prepareExchangedData(
99
            [
100
                'agses' => isKeyExistingAndEqual('agses_authentication_enabled', 1, $SETTINGS) === true ? true : false,
101
                'google' => isKeyExistingAndEqual('google_authentication', 1, $SETTINGS) === true ? true : false,
102
                'yubico' => isKeyExistingAndEqual('yubico_authentication', 1, $SETTINGS) === true ? true : false,
103
                'duo' => isKeyExistingAndEqual('duo', 1, $SETTINGS) === true ? true : false,
104
            ],
105
            'encode'
106
        ),
107
        'key' => $session->get('key'),
108
    ]);
109
    return false;
110
} elseif ($post_type === 'initiateSSOLogin') {
111
    //--------
112
    // Do initiateSSOLogin
113
    //--------
114
    //
115
116
    // Création d'une instance du contrôleur
117
    $OAuth2 = new OAuth2Controller($SETTINGS);
118
119
    // Redirection vers Azure pour l'authentification
120
    $OAuth2->redirect();
121
122
    // Encrypt data to return
123
    echo json_encode([
124
        'key' => $session->get('key'),
125
    ]);
126
    return false;
127
}
128
129
/**
130
 * Complete authentication of user through Teampass
131
 *
132
 * @param string $sentData Credentials
133
 * @param array $SETTINGS Teampass settings
134
 *
135
 * @return bool
136
 */
137
function identifyUser(string $sentData, array $SETTINGS): bool
138
{
139
    $antiXss = new AntiXSS();
140
    $session = SessionManager::getSession();
141
    $request = SymfonyRequest::createFromGlobals();
142
    $lang = new Language($session->get('user-language') ?? 'english');
143
    $session = SessionManager::getSession();
144
145
    // Prepare GET variables
146
    $sessionAdmin = $session->get('user-admin');
147
    $sessionPwdAttempts = $session->get('pwd_attempts');
148
    $sessionUrl = $session->get('user-initial_url');
149
    $server = [];
150
    $server['PHP_AUTH_USER'] =  $request->getUser();
151
    $server['PHP_AUTH_PW'] = $request->getPassword();
152
    
153
    // decrypt and retreive data in JSON format
154
    if ($session->get('key') === null) {
155
        $dataReceived = $sentData;
156
    } else {
157
        $dataReceived = prepareExchangedData(
158
            $sentData,
159
            'decode',
160
            $session->get('key')
161
        );
162
    }
163
164
    // Check if Duo auth is in progress and pass the pw and login back to the standard login process
165
    if(
166
        isKeyExistingAndEqual('duo', 1, $SETTINGS) === true
167
        && $dataReceived['user_2fa_selection'] === 'duo'
168
        && $session->get('user-duo_status') === 'IN_PROGRESS'
169
        && !empty($dataReceived['duo_state'])
170
    ){
171
        $key = hash('sha256', $dataReceived['duo_state']);
172
        $iv = substr(hash('sha256', $dataReceived['duo_state']), 0, 16);
173
        $duo_data_dec = openssl_decrypt(base64_decode($session->get('user-duo_data')), 'AES-256-CBC', $key, 0, $iv);
174
        // Clear the data from the Duo process to continue clean with the standard login process
175
        $session->set('user-duo_data','');
176
        if($duo_data_dec === false) {
177
            // Add failed authentication log
178
            addFailedAuthentication(filter_var($dataReceived['login'], FILTER_SANITIZE_FULL_SPECIAL_CHARS), getClientIpServer());
179
180
            echo prepareExchangedData(
181
                [
182
                    'error' => true,
183
                    'message' => $lang->get('duo_error_decrypt'),
184
                ],
185
                'encode'
186
            );
187
            return false;
188
        }
189
        $duo_data = unserialize($duo_data_dec);
190
        $dataReceived['pw'] = $duo_data['duo_pwd'];
191
        $dataReceived['login'] = $duo_data['duo_login'];
192
    }
193
194
    if(isset($dataReceived['pw']) === false || isset($dataReceived['login']) === false) {
195
        echo json_encode([
196
            'data' => prepareExchangedData(
197
                [
198
                    'error' => true,
199
                    'message' => $lang->get('ga_enter_credentials'),
200
                ],
201
                'encode'
202
            ),
203
            'key' => $session->get('key')
204
        ]);
205
        return false;
206
    }
207
208
    // prepare variables    
209
    $userCredentials = identifyGetUserCredentials(
210
        $SETTINGS,
211
        (string) $server['PHP_AUTH_USER'],
212
        (string) $server['PHP_AUTH_PW'],
213
        (string) filter_var($dataReceived['pw'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
214
        (string) filter_var($dataReceived['login'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)
215
    );
216
    $username = $userCredentials['username'];
217
    $passwordClear = $userCredentials['passwordClear'];
218
219
    // DO initial checks
220
    $userInitialData = identifyDoInitialChecks(
221
        $SETTINGS,
222
        (int) $sessionPwdAttempts,
223
        (string) $username,
224
        (int) $sessionAdmin,
225
        (string) $sessionUrl,
226
        (string) filter_var($dataReceived['user_2fa_selection'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)
227
    );
228
229
    // if user doesn't exist in Teampass then return error
230
    if ($userInitialData['error'] === true) {
231
        // Add log on error unless skip_anti_bruteforce flag is set to true
232
        if (empty($userInitialData['skip_anti_bruteforce'])
233
            || !$userInitialData['skip_anti_bruteforce']) {
234
235
            // Add failed authentication log
236
            addFailedAuthentication($username, getClientIpServer());
237
        }
238
239
        echo prepareExchangedData(
240
            $userInitialData['array'],
241
            'encode'
242
        );
243
        return false;
244
    }
245
246
    $userInfo = $userInitialData['userInfo'] + $dataReceived;
247
    $return = '';
248
249
    // Check if LDAP is enabled and user is in AD
250
    $userLdap = identifyDoLDAPChecks(
251
        $SETTINGS,
252
        $userInfo,
253
        (string) $username,
254
        (string) $passwordClear,
255
        (int) $sessionAdmin,
256
        (string) $sessionUrl,
257
        (int) $sessionPwdAttempts
258
    );
259
    if ($userLdap['error'] === true) {
260
        // Add failed authentication log
261
        addFailedAuthentication($username, getClientIpServer());
262
263
        // deepcode ignore ServerLeak: File and path are secured directly inside the function decryptFile()
264
        echo prepareExchangedData(
265
            $userLdap['array'],
266
            'encode'
267
        );
268
        return false;
269
    }
270
    if (isset($userLdap['user_info']) === true && (int) $userLdap['user_info']['has_been_created'] === 1) {
271
        // Add failed authentication log
272
        addFailedAuthentication($username, getClientIpServer());
273
274
        echo json_encode([
275
            'data' => prepareExchangedData(
276
                [
277
                    'error' => true,
278
                    'message' => '',
279
                    'extra' => 'ad_user_created',
280
                ],
281
                'encode'
282
            ),
283
            'key' => $session->get('key')
284
        ]);
285
        return false;
286
    }
287
288
    // Should we create new oauth2 user?
289
    $userOauth2 = createOauth2User(
290
        (array) $SETTINGS,
291
        (array) $userInfo,
292
        (string) $username,
293
        (string) $passwordClear,
294
        (int) $userLdap['user_info']['has_been_created']
295
    );
296
    if ($userOauth2['error'] === true) {
297
        $session->set('userOauth2Info', '');
298
299
        // Add failed authentication log
300
        addFailedAuthentication($username, getClientIpServer());
301
302
        // deepcode ignore ServerLeak: File and path are secured directly inside the function decryptFile()        
303
        echo prepareExchangedData(
304
            [
305
                'error' => true,
306
                'message' => $lang->get($userOauth2['message']),
307
            ],
308
            'encode'
309
        );
310
        return false;
311
    }
312
313
    // Check user and password
314
    if ($userLdap['userPasswordVerified'] === false && $userOauth2['userPasswordVerified'] === false
315
        && checkCredentials($passwordClear, $userInfo) !== true
316
    ) {
317
        // Add failed authentication log
318
        addFailedAuthentication($username, getClientIpServer());
319
320
        echo prepareExchangedData(
321
            [
322
                'value' => '',
323
                'error' => true,
324
                'message' => $lang->get('error_bad_credentials'),
325
            ],
326
            'encode'
327
        );
328
        return false;
329
    }
330
331
    // Check if MFA is required
332
    if ((isOneVarOfArrayEqualToValue(
333
                [
334
                    (int) $SETTINGS['yubico_authentication'],
335
                    (int) $SETTINGS['google_authentication'],
336
                    (int) $SETTINGS['duo']
337
                ],
338
                1
339
            ) === true)
340
        && (((int) $userInfo['admin'] !== 1 && (int) $userInfo['mfa_enabled'] === 1 && $userInfo['mfa_auth_requested_roles'] === true)
341
        || ((int) $SETTINGS['admin_2fa_required'] === 1 && (int) $userInfo['admin'] === 1))
342
    ) {
343
        // Check user against MFA method if selected
344
        $userMfa = identifyDoMFAChecks(
345
            $SETTINGS,
346
            $userInfo,
347
            $dataReceived,
348
            $userInitialData,
349
            (string) $username
350
        );
351
        if ($userMfa['error'] === true) {
352
            // Add failed authentication log
353
            addFailedAuthentication($username, getClientIpServer());
354
355
            echo prepareExchangedData(
356
                [
357
                    'error' => true,
358
                    'message' => $userMfa['mfaData']['message'],
359
                    'mfaStatus' => $userMfa['mfaData']['mfaStatus'],
360
                ],
361
                'encode'
362
            );
363
            return false;
364
        } elseif ($userMfa['mfaQRCodeInfos'] === true) {
365
            // Add failed authentication log
366
            addFailedAuthentication($username, getClientIpServer());
367
368
            // Case where user has initiated Google Auth
369
            // Return QR code
370
            echo prepareExchangedData(
371
                [
372
                    'value' => $userMfa['mfaData']['value'],
373
                    'user_admin' => isset($sessionAdmin) ? (int) $sessionAdmin : 0,
374
                    'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
375
                    'pwd_attempts' => (int) $sessionPwdAttempts,
376
                    'error' => false,
377
                    'message' => $userMfa['mfaData']['message'],
378
                    'mfaStatus' => $userMfa['mfaData']['mfaStatus'],
379
                ],
380
                'encode'
381
            );
382
            return false;
383
        } elseif ($userMfa['duo_url_ready'] === true) {
384
            // Add failed authentication log
385
            addFailedAuthentication($username, getClientIpServer());
386
387
            // Case where user has initiated Duo Auth
388
            // Return the DUO redirect URL
389
            echo prepareExchangedData(
390
                [
391
                    'user_admin' => isset($sessionAdmin) ? (int) $sessionAdmin : 0,
392
                    'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
393
                    'pwd_attempts' => (int) $sessionPwdAttempts,
394
                    'error' => false,
395
                    'message' => $userMfa['mfaData']['message'],
396
                    'duo_url_ready' => $userMfa['mfaData']['duo_url_ready'],
397
                    'duo_redirect_url' => $userMfa['mfaData']['duo_redirect_url'],
398
                    'mfaStatus' => $userMfa['mfaData']['mfaStatus'],
399
                ],
400
                'encode'
401
            );
402
            return false;
403
        }
404
    }
405
406
    // Can connect if
407
    // 1- no LDAP mode + user enabled + pw ok
408
    // 2- LDAP mode + user enabled + ldap connection ok + user is not admin
409
    // 3- LDAP mode + user enabled + pw ok + usre is admin
410
    // This in order to allow admin by default to connect even if LDAP is activated
411
    if (canUserGetLog(
412
            $SETTINGS,
413
            (int) $userInfo['disabled'],
414
            $username,
415
            $userLdap['ldapConnection']
416
        ) === true
417
    ) {
418
        $session->set('pwd_attempts', 0);
419
420
        // Check if any unsuccessfull login tries exist
421
        $attemptsInfos = handleLoginAttempts(
0 ignored issues
show
Unused Code introduced by
The assignment to $attemptsInfos is dead and can be removed.
Loading history...
422
            $userInfo['id'],
423
            $userInfo['login'],
424
            $userInfo['last_connexion'],
425
            $username,
426
            $SETTINGS,
427
        );
428
429
        // Avoid unlimited session.
430
        $max_time = isset($SETTINGS['maximum_session_expiration_time']) ? (int) $SETTINGS['maximum_session_expiration_time'] : 60;
431
        $session_time = max(60, min($dataReceived['duree_session'], $max_time));
432
        $lifetime = time() + ($session_time * 60);
433
434
        // Save old key
435
        $old_key = $session->get('key');
436
437
        // Good practice: reset PHPSESSID and key after successful authentication
438
        $session->migrate();
439
        $session->set('key', generateQuickPassword(30, false));
440
441
        // Save account in SESSION
442
        $session->set('user-login', stripslashes($username));
443
        $session->set('user-name', empty($userInfo['name']) === false ? stripslashes($userInfo['name']) : '');
444
        $session->set('user-lastname', empty($userInfo['lastname']) === false ? stripslashes($userInfo['lastname']) : '');
445
        $session->set('user-id', (int) $userInfo['id']);
446
        $session->set('user-admin', (int) $userInfo['admin']);
447
        $session->set('user-manager', (int) $userInfo['gestionnaire']);
448
        $session->set('user-can_manage_all_users', $userInfo['can_manage_all_users']);
449
        $session->set('user-read_only', $userInfo['read_only']);
450
        $session->set('user-last_pw_change', $userInfo['last_pw_change']);
451
        $session->set('user-last_pw', $userInfo['last_pw']);
452
        $session->set('user-force_relog', $userInfo['force-relog']);
453
        $session->set('user-can_create_root_folder', $userInfo['can_create_root_folder']);
454
        $session->set('user-email', $userInfo['email']);
455
        //$session->set('user-ga', $userInfo['ga']);
456
        $session->set('user-avatar', $userInfo['avatar']);
457
        $session->set('user-avatar_thumb', $userInfo['avatar_thumb']);
458
        $session->set('user-upgrade_needed', $userInfo['upgrade_needed']);
459
        $session->set('user-is_ready_for_usage', $userInfo['is_ready_for_usage']);
460
        $session->set('user-personal_folder_enabled', $userInfo['personal_folder']);
461
        $session->set(
462
            'user-tree_load_strategy',
463
            (isset($userInfo['treeloadstrategy']) === false || empty($userInfo['treeloadstrategy']) === true) ? 'full' : $userInfo['treeloadstrategy']
464
        );
465
        $session->set(
466
            'user-split_view_mode',
467
            (isset($userInfo['split_view_mode']) === false || empty($userInfo['split_view_mode']) === true) ? 0 : $userInfo['split_view_mode']
468
        );
469
        $session->set('user-language', $userInfo['user_language']);
470
        $session->set('user-timezone', $userInfo['usertimezone']);
471
        $session->set('user-keys_recovery_time', $userInfo['keys_recovery_time']);
472
        
473
        // manage session expiration
474
        $session->set('user-session_duration', (int) $lifetime);
475
476
        // User signature keys
477
        $returnKeys = prepareUserEncryptionKeys($userInfo, $passwordClear);  
478
        $session->set('user-private_key', $returnKeys['private_key_clear']);
479
        $session->set('user-public_key', $returnKeys['public_key']);
480
481
        // Automatically detect LDAP password changes.
482
        if ($userInfo['auth_type'] === 'ldap' && $returnKeys['private_key_clear'] === '') {
483
            // Add special "recrypt-private-key" in database profile.
484
            DB::update(
485
                prefixTable('users'),
486
                array(
487
                    'special' => 'recrypt-private-key',
488
                ),
489
                'id = %i',
490
                $userInfo['id']
491
            );
492
493
            // Store new value in userInfos.
494
            $userInfo['special'] = 'recrypt-private-key';
495
        }
496
497
        // API key
498
        $session->set(
499
            'user-api_key',
500
            empty($userInfo['api_key']) === false ? base64_decode(decryptUserObjectKey($userInfo['api_key'], $returnKeys['private_key_clear'])) : '',
501
        );
502
        
503
        $session->set('user-special', $userInfo['special']);
504
        $session->set('user-auth_type', $userInfo['auth_type']);
505
506
        // check feedback regarding user password validity
507
        $return = checkUserPasswordValidity(
508
            $userInfo,
509
            (int) $session->get('user-num_days_before_exp'),
510
            (int) $session->get('user-last_pw_change'),
511
            $SETTINGS
512
        );
513
        $session->set('user-validite_pw', $return['validite_pw']);
514
        $session->set('user-last_pw_change', $return['last_pw_change']);
515
        $session->set('user-num_days_before_exp', $return['numDaysBeforePwExpiration']);
516
        $session->set('user-force_relog', $return['user_force_relog']);
517
        
518
        $session->set('user-last_connection', empty($userInfo['last_connexion']) === false ? (int) $userInfo['last_connexion'] : (int) time());
519
        $session->set('user-latest_items', empty($userInfo['latest_items']) === false ? explode(';', $userInfo['latest_items']) : []);
520
        $session->set('user-favorites', empty($userInfo['favourites']) === false ? explode(';', $userInfo['favourites']) : []);
521
        $session->set('user-accessible_folders', empty($userInfo['groupes_visibles']) === false ? explode(';', $userInfo['groupes_visibles']) : []);
522
        $session->set('user-no_access_folders', empty($userInfo['groupes_interdits']) === false ? explode(';', $userInfo['groupes_interdits']) : []);
523
        
524
        // User's roles
525
        if (strpos($userInfo['fonction_id'] !== NULL ? (string) $userInfo['fonction_id'] : '', ',') !== -1) {
526
            // Convert , to ;
527
            $userInfo['fonction_id'] = str_replace(',', ';', (string) $userInfo['fonction_id']);
528
            DB::update(
529
                prefixTable('users'),
530
                [
531
                    'fonction_id' => $userInfo['fonction_id'],
532
                ],
533
                'id = %i',
534
                $session->get('user-id')
535
            );
536
        }
537
        // Append with roles from AD groups
538
        if (is_null($userInfo['roles_from_ad_groups']) === false) {
539
            $userInfo['fonction_id'] = empty($userInfo['fonction_id'])  === true ? $userInfo['roles_from_ad_groups'] : $userInfo['fonction_id']. ';' . $userInfo['roles_from_ad_groups'];
540
        }
541
        // store
542
        $session->set('user-roles', $userInfo['fonction_id']);
543
        $session->set('user-roles_array', array_unique(array_filter(explode(';', $userInfo['fonction_id']))));
544
        
545
        // build array of roles
546
        $session->set('user-pw_complexity', 0);
547
        $session->set('system-array_roles', []);
548
        if (count($session->get('user-roles_array')) > 0) {
549
            $rolesList = DB::query(
550
                'SELECT id, title, complexity
551
                FROM ' . prefixTable('roles_title') . '
552
                WHERE id IN %li',
553
                $session->get('user-roles_array')
554
            );
555
            $excludeUser = isset($SETTINGS['exclude_user']) ? str_contains($session->get('user-login'), $SETTINGS['exclude_user']) : false;
556
            $adjustPermissions = ($session->get('user-id') >= 1000000 && !$excludeUser && (isset($SETTINGS['admin_needle']) || isset($SETTINGS['manager_needle']) || isset($SETTINGS['tp_manager_needle']) || isset($SETTINGS['read_only_needle'])));
557
            if ($adjustPermissions) {
558
                $userInfo['admin'] = $userInfo['gestionnaire'] = $userInfo['can_manage_all_users'] = $userInfo['read_only'] = 0;
559
            }
560
            foreach ($rolesList as $role) {
561
                SessionManager::addRemoveFromSessionAssociativeArray(
562
                    'system-array_roles',
563
                    [
564
                        'id' => $role['id'],
565
                        'title' => $role['title'],
566
                    ],
567
                    'add'
568
                );
569
                
570
                if ($adjustPermissions) {
571
                    if (isset($SETTINGS['admin_needle']) && str_contains($role['title'], $SETTINGS['admin_needle'])) {
572
                        $userInfo['gestionnaire'] = $userInfo['can_manage_all_users'] = $userInfo['read_only'] = 0;
573
                        $userInfo['admin'] = 1;
574
                    }    
575
                    if (isset($SETTINGS['manager_needle']) && str_contains($role['title'], $SETTINGS['manager_needle'])) {
576
                        $userInfo['admin'] = $userInfo['can_manage_all_users'] = $userInfo['read_only'] = 0;
577
                        $userInfo['gestionnaire'] = 1;
578
                    }
579
                    if (isset($SETTINGS['tp_manager_needle']) && str_contains($role['title'], $SETTINGS['tp_manager_needle'])) {
580
                        $userInfo['admin'] = $userInfo['gestionnaire'] = $userInfo['read_only'] = 0;
581
                        $userInfo['can_manage_all_users'] = 1;
582
                    }
583
                    if (isset($SETTINGS['read_only_needle']) && str_contains($role['title'], $SETTINGS['read_only_needle'])) {
584
                        $userInfo['admin'] = $userInfo['gestionnaire'] = $userInfo['can_manage_all_users'] = 0;
585
                        $userInfo['read_only'] = 1;
586
                    }
587
                }
588
589
                // get highest complexity
590
                if ($session->get('user-pw_complexity') < (int) $role['complexity']) {
591
                    $session->set('user-pw_complexity', (int) $role['complexity']);
592
                }
593
            }
594
            if ($adjustPermissions) {
595
                $session->set('user-admin', (int) $userInfo['admin']);
596
                $session->set('user-manager', (int) $userInfo['gestionnaire']);
597
                $session->set('user-can_manage_all_users',(int)  $userInfo['can_manage_all_users']);
598
                $session->set('user-read_only', (int) $userInfo['read_only']);
599
                DB::update(
600
                    prefixTable('users'),
601
                    [
602
                        'admin' => $userInfo['admin'],
603
                        'gestionnaire' => $userInfo['gestionnaire'],
604
                        'can_manage_all_users' => $userInfo['can_manage_all_users'],
605
                        'read_only' => $userInfo['read_only'],
606
                    ],
607
                    'id = %i',
608
                    $session->get('user-id')
609
                );
610
            }
611
        }
612
613
        // Set some settings
614
        $SETTINGS['update_needed'] = '';
615
616
        // Update table
617
        DB::update(
618
            prefixTable('users'),
619
            array_merge(
620
                [
621
                    'key_tempo' => $session->get('key'),
622
                    'last_connexion' => time(),
623
                    'timestamp' => time(),
624
                    'disabled' => 0,
625
                    'session_end' => $session->get('user-session_duration'),
626
                    'user_ip' => $dataReceived['client'],
627
                ],
628
                $returnKeys['update_keys_in_db']
629
            ),
630
            'id=%i',
631
            $userInfo['id']
632
        );
633
        
634
        // Get user's rights
635
        if ($userLdap['user_initial_creation_through_external_ad'] === true || $userOauth2['retExternalAD']['has_been_created'] === 1) {
636
            // is new LDAP user. Show only his personal folder
637
            if ($SETTINGS['enable_pf_feature'] === '1') {
638
                $session->set('user-personal_visible_folders', [$userInfo['id']]);
639
                $session->set('user-personal_folders', [$userInfo['id']]);
640
            } else {
641
                $session->set('user-personal_visible_folders', []);
642
                $session->set('user-personal_folders', []);
643
            }
644
            $session->set('user-all_non_personal_folders', []);
645
            $session->set('user-roles_array', []);
646
            $session->set('user-read_only_folders', []);
647
            $session->set('user-list_folders_limited', []);
648
            $session->set('system-list_folders_editable_by_role', []);
649
            $session->set('system-list_restricted_folders_for_items', []);
650
            $session->set('user-nb_folders', 1);
651
            $session->set('user-nb_roles', 1);
652
        } else {
653
            identifyUserRights(
654
                $userInfo['groupes_visibles'],
655
                $session->get('user-no_access_folders'),
656
                $userInfo['admin'],
657
                $userInfo['fonction_id'],
658
                $SETTINGS
659
            );
660
        }
661
        // Get some more elements
662
        $session->set('system-screen_height', $dataReceived['screenHeight']);
663
664
        // Get last seen items
665
        $session->set('user-latest_items_tab', []);
666
        $session->set('user-nb_roles', 0);
667
        foreach ($session->get('user-latest_items') as $item) {
668
            if (! empty($item)) {
669
                $dataLastItems = DB::queryFirstRow(
670
                    'SELECT id,label,id_tree
671
                    FROM ' . prefixTable('items') . '
672
                    WHERE id=%i',
673
                    $item
674
                );
675
                SessionManager::addRemoveFromSessionAssociativeArray(
676
                    'user-latest_items_tab',
677
                    [
678
                        'id' => $item,
679
                        'label' => $dataLastItems['label'],
680
                        'url' => 'index.php?page=items&amp;group=' . $dataLastItems['id_tree'] . '&amp;id=' . $item,
681
                    ],
682
                    'add'
683
                );
684
            }
685
        }
686
687
        // Get cahce tree info
688
        $cacheTreeData = DB::queryFirstRow(
689
            'SELECT visible_folders
690
            FROM ' . prefixTable('cache_tree') . '
691
            WHERE user_id=%i',
692
            (int) $session->get('user-id')
693
        );
694
        if (DB::count() > 0 && empty($cacheTreeData['visible_folders']) === true) {
695
            $session->set('user-cache_tree', '');
696
            // Prepare new task
697
            DB::insert(
698
                prefixTable('background_tasks'),
699
                array(
700
                    'created_at' => time(),
701
                    'process_type' => 'user_build_cache_tree',
702
                    'arguments' => json_encode([
703
                        'user_id' => (int) $session->get('user-id'),
704
                    ], JSON_HEX_QUOT | JSON_HEX_TAG),
705
                    'updated_at' => null,
706
                    'finished_at' => null,
707
                    'output' => null,
708
                )
709
            );
710
        } else {
711
            $session->set('user-cache_tree', $cacheTreeData['visible_folders']);
712
        }
713
714
        // send back the random key
715
        $return = $dataReceived['randomstring'];
716
        // Send email
717
        if (
718
            isKeyExistingAndEqual('enable_send_email_on_user_login', 1, $SETTINGS) === true
719
            && (int) $sessionAdmin !== 1
720
        ) {
721
            // get all Admin users
722
            $val = DB::queryFirstRow('SELECT email FROM ' . prefixTable('users') . " WHERE admin = %i and email != ''", 1);
723
            if (DB::count() > 0) {
724
                // Add email to table
725
                prepareSendingEmail(
726
                    $lang->get('email_subject_on_user_login'),
727
                    str_replace(
728
                        [
729
                            '#tp_user#',
730
                            '#tp_date#',
731
                            '#tp_time#',
732
                        ],
733
                        [
734
                            ' ' . $session->get('user-login') . ' (IP: ' . getClientIpServer() . ')',
735
                            date($SETTINGS['date_format'], (int) $session->get('user-last_connection')),
736
                            date($SETTINGS['time_format'], (int) $session->get('user-last_connection')),
737
                        ],
738
                        $lang->get('email_body_on_user_login')
739
                    ),
740
                    $val['email'],
741
                    $lang->get('administrator')
742
                );
743
            }
744
        }
745
        
746
        // Ensure Complexity levels are translated
747
        defineComplexity();
748
        echo prepareExchangedData(
749
            [
750
                'value' => $return,
751
                'user_id' => $session->get('user-id') !== null ? $session->get('user-id') : '',
752
                'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
753
                'initial_url' => $antiXss->xss_clean($sessionUrl),
754
                'pwd_attempts' => 0,
755
                'error' => false,
756
                'message' => $session->has('user-upgrade_needed') && (int) $session->get('user-upgrade_needed') && (int) $session->get('user-upgrade_needed') === 1 ? 'ask_for_otc' : '',
757
                'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
758
                'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
759
                'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
760
                'private_key_conform' => $session->get('user-id') !== null
761
                    && empty($session->get('user-private_key')) === false
762
                    && $session->get('user-private_key') !== 'none' ? true : false,
763
                'session_key' => $session->get('key'),
764
                'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
765
                'upgrade_needed' => isset($userInfo['upgrade_needed']) === true ? (int) $userInfo['upgrade_needed'] : 0,
766
                'special' => isset($userInfo['special']) === true ? (int) $userInfo['special'] : 0,
767
                'split_view_mode' => isset($userInfo['split_view_mode']) === true ? (int) $userInfo['split_view_mode'] : 0,
768
                'validite_pw' => $session->get('user-validite_pw') !== null ? $session->get('user-validite_pw') : '',
769
                'num_days_before_exp' => $session->get('user-num_days_before_exp') !== null ? (int) $session->get('user-num_days_before_exp') : '',
770
            ],
771
            'encode',
772
            $old_key
773
        );
774
    
775
        return true;
776
777
    } elseif ((int) $userInfo['disabled'] === 1) {
778
        // User and password is okay but account is locked
779
        echo prepareExchangedData(
780
            [
781
                'value' => $return,
782
                'user_id' => $session->get('user-id') !== null ? (int) $session->get('user-id') : '',
783
                'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
784
                'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
785
                'pwd_attempts' => 0,
786
                'error' => 'user_is_locked',
787
                'message' => $lang->get('account_is_locked'),
788
                'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
789
                'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
790
                'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
791
                'private_key_conform' => $session->has('user-private_key') && null !== $session->get('user-private_key')
792
                    && empty($session->get('user-private_key')) === false
793
                    && $session->get('user-private_key') !== 'none' ? true : false,
794
                'session_key' => $session->get('key'),
795
                'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
796
            ],
797
            'encode'
798
        );
799
        return false;
800
    }
801
802
    echo prepareExchangedData(
803
        [
804
            'value' => $return,
805
            'user_id' => $session->get('user-id') !== null ? (int) $session->get('user-id') : '',
806
            'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
807
            'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
808
            'pwd_attempts' => (int) $sessionPwdAttempts,
809
            'error' => true,
810
            'message' => $lang->get('error_not_allowed_to_authenticate'),
811
            'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
812
            'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
813
            'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
814
            'private_key_conform' => $session->get('user-id') !== null
815
                    && empty($session->get('user-private_key')) === false
816
                    && $session->get('user-private_key') !== 'none' ? true : false,
817
            'session_key' => $session->get('key'),
818
            'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
819
        ],
820
        'encode'
821
    );
822
    return false;
823
}
824
825
/**
826
 * Check if any unsuccessfull login tries exist
827
 *
828
 * @param int       $userInfoId
829
 * @param string    $userInfoLogin
830
 * @param string    $userInfoLastConnection
831
 * @param string    $username
832
 * @param array     $SETTINGS
833
 * @return array
834
 */
835
function handleLoginAttempts(
836
    $userInfoId,
837
    $userInfoLogin,
838
    $userInfoLastConnection,
839
    $username,
840
    $SETTINGS
841
) : array
842
{
843
    $rows = DB::query(
844
        'SELECT date
845
        FROM ' . prefixTable('log_system') . "
846
        WHERE field_1 = %s
847
        AND type = 'failed_auth'
848
        AND label = 'password_is_not_correct'
849
        AND date >= %s AND date < %s",
850
        $userInfoLogin,
851
        $userInfoLastConnection,
852
        time()
853
    );
854
    $arrAttempts = [];
855
    if (DB::count() > 0) {
856
        foreach ($rows as $record) {
857
            array_push(
858
                $arrAttempts,
859
                date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], (int) $record['date'])
860
            );
861
        }
862
    }
863
    
864
865
    // Log into DB the user's connection
866
    if (isKeyExistingAndEqual('log_connections', 1, $SETTINGS) === true) {
867
        logEvents($SETTINGS, 'user_connection', 'connection', (string) $userInfoId, stripslashes($username));
868
    }
869
870
    return [
871
        'attemptsList' => $arrAttempts,
872
        'attemptsCount' => count($rows),
873
    ];
874
}
875
876
877
/**
878
 * Can you user get logged into main page
879
 *
880
 * @param array     $SETTINGS
881
 * @param int       $userInfoDisabled
882
 * @param string    $username
883
 * @param bool      $ldapConnection
884
 *
885
 * @return boolean
886
 */
887
function canUserGetLog(
888
    $SETTINGS,
889
    $userInfoDisabled,
890
    $username,
891
    $ldapConnection
892
) : bool
893
{
894
    include_once $SETTINGS['cpassman_dir'] . '/sources/main.functions.php';
895
896
    if ((int) $userInfoDisabled === 1) {
897
        return false;
898
    }
899
900
    if (isKeyExistingAndEqual('ldap_mode', 0, $SETTINGS) === true) {
901
        return true;
902
    }
903
    
904
    if (isKeyExistingAndEqual('ldap_mode', 1, $SETTINGS) === true 
905
        && (
906
            ($ldapConnection === true && $username !== 'admin')
907
            || $username === 'admin'
908
        )
909
    ) {
910
        return true;
911
    }
912
913
    if (isKeyExistingAndEqual('ldap_and_local_authentication', 1, $SETTINGS) === true
914
        && isset($SETTINGS['ldap_mode']) === true && in_array($SETTINGS['ldap_mode'], ['1', '2']) === true
915
    ) {
916
        return true;
917
    }
918
919
    return false;
920
}
921
922
/**
923
 * 
924
 * Prepare user keys
925
 * 
926
 * @param array $userInfo   User account information
927
 * @param string $passwordClear
928
 *
929
 * @return array
930
 */
931
function prepareUserEncryptionKeys($userInfo, $passwordClear) : array
932
{
933
    if (is_null($userInfo['private_key']) === true || empty($userInfo['private_key']) === true || $userInfo['private_key'] === 'none') {
934
        // No keys have been generated yet
935
        // Create them
936
        $userKeys = generateUserKeys($passwordClear);
937
938
        return [
939
            'public_key' => $userKeys['public_key'],
940
            'private_key_clear' => $userKeys['private_key_clear'],
941
            'update_keys_in_db' => [
942
                'public_key' => $userKeys['public_key'],
943
                'private_key' => $userKeys['private_key'],
944
            ],
945
        ];
946
    } 
947
    
948
    if ($userInfo['special'] === 'generate-keys') {
949
        return [
950
            'public_key' => $userInfo['public_key'],
951
            'private_key_clear' => '',
952
            'update_keys_in_db' => [],
953
        ];
954
    }
955
    
956
    // Don't perform this in case of special login action
957
    if ($userInfo['special'] === 'otc_is_required_on_next_login' || $userInfo['special'] === 'user_added_from_ldap') {
958
        return [
959
            'public_key' => $userInfo['public_key'],
960
            'private_key_clear' => '',
961
            'update_keys_in_db' => [],
962
        ];
963
    }
964
    
965
    // Uncrypt private key
966
    return [
967
        'public_key' => $userInfo['public_key'],
968
        'private_key_clear' => decryptPrivateKey($passwordClear, $userInfo['private_key']),
969
        'update_keys_in_db' => [],
970
    ];
971
}
972
973
974
/**
975
 * CHECK PASSWORD VALIDITY
976
 * Don't take into consideration if LDAP in use
977
 * 
978
 * @param array $userInfo User account information
979
 * @param int $numDaysBeforePwExpiration Number of days before password expiration
980
 * @param int $lastPwChange Last password change
981
 * @param array $SETTINGS Teampass settings
982
 *
983
 * @return array
984
 */
985
function checkUserPasswordValidity(array $userInfo, int $numDaysBeforePwExpiration, int $lastPwChange, array $SETTINGS)
986
{
987
    if (isKeyExistingAndEqual('ldap_mode', 1, $SETTINGS) === true && $userInfo['auth_type'] !== 'local') {
988
        return [
989
            'validite_pw' => true,
990
            'last_pw_change' => $userInfo['last_pw_change'],
991
            'user_force_relog' => '',
992
            'numDaysBeforePwExpiration' => '',
993
        ];
994
    }
995
    
996
    if (isset($userInfo['last_pw_change']) === true) {
997
        if ((int) $SETTINGS['pw_life_duration'] === 0) {
998
            return [
999
                'validite_pw' => true,
1000
                'last_pw_change' => '',
1001
                'user_force_relog' => 'infinite',
1002
                'numDaysBeforePwExpiration' => '',
1003
            ];
1004
        } elseif ((int) $SETTINGS['pw_life_duration'] > 0) {
1005
            $numDaysBeforePwExpiration = (int) $SETTINGS['pw_life_duration'] - round(
1006
                (mktime(0, 0, 0, (int) date('m'), (int) date('d'), (int) date('y')) - $userInfo['last_pw_change']) / (24 * 60 * 60)
1007
            );
1008
            return [
1009
                'validite_pw' => $numDaysBeforePwExpiration <= 0 ? false : true,
1010
                'last_pw_change' => $userInfo['last_pw_change'],
1011
                'user_force_relog' => 'infinite',
1012
                'numDaysBeforePwExpiration' => (int) $numDaysBeforePwExpiration,
1013
            ];
1014
        } else {
1015
            return [
1016
                'validite_pw' => false,
1017
                'last_pw_change' => '',
1018
                'user_force_relog' => '',
1019
                'numDaysBeforePwExpiration' => '',
1020
            ];
1021
        }
1022
    } else {
1023
        return [
1024
            'validite_pw' => false,
1025
            'last_pw_change' => '',
1026
            'user_force_relog' => '',
1027
            'numDaysBeforePwExpiration' => '',
1028
        ];
1029
    }
1030
}
1031
1032
1033
/**
1034
 * Authenticate a user through AD/LDAP.
1035
 *
1036
 * @param string $username      Username
1037
 * @param array $userInfo       User account information
1038
 * @param string $passwordClear Password
1039
 * @param array $SETTINGS       Teampass settings
1040
 *
1041
 * @return array
1042
 */
1043
function authenticateThroughAD(string $username, array $userInfo, string $passwordClear, array $SETTINGS): array
1044
{
1045
    $session = SessionManager::getSession();
1046
    $lang = new Language($session->get('user-language') ?? 'english');
1047
    
1048
    try {
1049
        // Get LDAP connection and handler
1050
        $ldapHandler = initializeLdapConnection($SETTINGS);
1051
        
1052
        // Authenticate user
1053
        $authResult = authenticateUser($username, $passwordClear, $ldapHandler, $SETTINGS, $lang);
1054
        if ($authResult['error']) {
1055
            return $authResult;
1056
        }
1057
        
1058
        $userADInfos = $authResult['user_info'];
1059
        
1060
        // Verify account expiration
1061
        if (isAccountExpired($userADInfos)) {
1062
            return [
1063
                'error' => true,
1064
                'message' => $lang->get('error_ad_user_expired'),
1065
            ];
1066
        }
1067
        
1068
        // Handle user creation if needed
1069
        if ($userInfo['ldap_user_to_be_created']) {
1070
            $userInfo = handleNewUser($username, $passwordClear, $userADInfos, $userInfo, $SETTINGS, $lang);
1071
        }
1072
        
1073
        // Get and handle user groups
1074
        $userGroupsData = getUserGroups($userADInfos, $ldapHandler, $SETTINGS);
1075
        handleUserADGroups($username, $userInfo, $userGroupsData['userGroups'], $SETTINGS);
1076
        
1077
        // Finalize authentication
1078
        finalizeAuthentication($userInfo, $passwordClear, $SETTINGS);
1079
        
1080
        return [
1081
            'error' => false,
1082
            'message' => '',
1083
            'user_info' => $userInfo,
1084
        ];
1085
        
1086
    } catch (Exception $e) {
1087
        return [
1088
            'error' => true,
1089
            'message' => "Error: " . $e->getMessage(),
1090
        ];
1091
    }
1092
}
1093
1094
/**
1095
 * Initialize LDAP connection based on type
1096
 * 
1097
 * @param array $SETTINGS Teampass settings
1098
 * @return array Contains connection and type-specific handler
1099
 * @throws Exception
1100
 */
1101
function initializeLdapConnection(array $SETTINGS): array
1102
{
1103
    $ldapExtra = new LdapExtra($SETTINGS);
1104
    $ldapConnection = $ldapExtra->establishLdapConnection();
1105
    
1106
    switch ($SETTINGS['ldap_type']) {
1107
        case 'ActiveDirectory':
1108
            return [
1109
                'connection' => $ldapConnection,
1110
                'handler' => new ActiveDirectoryExtra(),
1111
                'type' => 'ActiveDirectory'
1112
            ];
1113
        case 'OpenLDAP':
1114
            return [
1115
                'connection' => $ldapConnection,
1116
                'handler' => new OpenLdapExtra(),
1117
                'type' => 'OpenLDAP'
1118
            ];
1119
        default:
1120
            throw new Exception("Unsupported LDAP type: " . $SETTINGS['ldap_type']);
1121
    }
1122
}
1123
1124
/**
1125
 * Authenticate user against LDAP
1126
 * 
1127
 * @param string $username Username
1128
 * @param string $passwordClear Password
1129
 * @param array $ldapHandler LDAP connection and handler
1130
 * @param array $SETTINGS Teampass settings
1131
 * @param Language $lang Language instance
1132
 * @return array Authentication result
1133
 */
1134
function authenticateUser(string $username, string $passwordClear, array $ldapHandler, array $SETTINGS, Language $lang): array
1135
{
1136
    try {
1137
        $userAttribute = $SETTINGS['ldap_user_attribute'] ?? 'samaccountname';
1138
        $userADInfos = $ldapHandler['connection']->query()
1139
            ->where($userAttribute, '=', $username)
1140
            ->firstOrFail();
1141
        
1142
        // Verify user status for ActiveDirectory
1143
        if ($ldapHandler['type'] === 'ActiveDirectory' && !$ldapHandler['handler']->userIsEnabled((string) $userADInfos['dn'], $ldapHandler['connection'])) {
1144
            return [
1145
                'error' => true,
1146
                'message' => "Error: User is not enabled"
1147
            ];
1148
        }
1149
        
1150
        // Attempt authentication
1151
        $authIdentifier = $ldapHandler['type'] === 'ActiveDirectory' 
1152
            ? $userADInfos['userprincipalname'][0] 
1153
            : $userADInfos['dn'];
1154
            
1155
        if (!$ldapHandler['connection']->auth()->attempt($authIdentifier, $passwordClear)) {
1156
            return [
1157
                'error' => true,
1158
                'message' => "Error: User is not authenticated"
1159
            ];
1160
        }
1161
        
1162
        return [
1163
            'error' => false,
1164
            'user_info' => $userADInfos
1165
        ];
1166
        
1167
    } catch (\LdapRecord\Query\ObjectNotFoundException $e) {
1168
        return [
1169
            'error' => true,
1170
            'message' => $lang->get('error_bad_credentials')
1171
        ];
1172
    }
1173
}
1174
1175
/**
1176
 * Check if user account is expired
1177
 * 
1178
 * @param array $userADInfos User AD information
1179
 * @return bool
1180
 */
1181
function isAccountExpired(array $userADInfos): bool
1182
{
1183
    return (isset($userADInfos['shadowexpire'][0]) && (int) $userADInfos['shadowexpire'][0] === 1)
1184
        || (isset($userADInfos['accountexpires'][0]) 
1185
            && (int) $userADInfos['accountexpires'][0] < time() 
1186
            && (int) $userADInfos['accountexpires'][0] !== 0);
1187
}
1188
1189
/**
1190
 * Handle creation of new user
1191
 * 
1192
 * @param string $username Username
1193
 * @param string $passwordClear Password
1194
 * @param array $userADInfos User AD information
1195
 * @param array $userInfo User information
1196
 * @param array $SETTINGS Teampass settings
1197
 * @param Language $lang Language instance
1198
 * @return array User information
1199
 */
1200
function handleNewUser(string $username, string $passwordClear, array $userADInfos, array $userInfo, array $SETTINGS, Language $lang): array
1201
{
1202
    $userInfo = externalAdCreateUser(
1203
        $username,
1204
        $passwordClear,
1205
        $userADInfos['mail'][0],
1206
        $userADInfos['givenname'][0],
1207
        $userADInfos['sn'][0],
1208
        'ldap',
1209
        [],
1210
        $SETTINGS
1211
    );
1212
1213
    handleUserKeys(
1214
        (int) $userInfo['id'],
1215
        $passwordClear,
1216
        (int) ($SETTINGS['maximum_number_of_items_to_treat'] ?? NUMBER_ITEMS_IN_BATCH),
1217
        uniqidReal(20),
1218
        true,
1219
        true,
1220
        true,
1221
        false,
1222
        $lang->get('email_body_user_config_2')
1223
    );
1224
1225
    $userInfo['has_been_created'] = 1;
1226
    return $userInfo;
1227
}
1228
1229
/**
1230
 * Get user groups based on LDAP type
1231
 * 
1232
 * @param array $userADInfos User AD information
1233
 * @param array $ldapHandler LDAP connection and handler
1234
 * @param array $SETTINGS Teampass settings
1235
 * @return array User groups
1236
 */
1237
function getUserGroups(array $userADInfos, array $ldapHandler, array $SETTINGS): array
1238
{
1239
    $dnAttribute = $SETTINGS['ldap_user_dn_attribute'] ?? 'distinguishedname';
1240
    
1241
    if ($ldapHandler['type'] === 'ActiveDirectory') {
1242
        return $ldapHandler['handler']->getUserADGroups(
1243
            $userADInfos[$dnAttribute][0],
1244
            $ldapHandler['connection'],
1245
            $SETTINGS
1246
        );
1247
    }
1248
    
1249
    if ($ldapHandler['type'] === 'OpenLDAP') {
1250
        return $ldapHandler['handler']->getUserADGroups(
1251
            $userADInfos['dn'],
1252
            $ldapHandler['connection'],
1253
            $SETTINGS
1254
        );
1255
    }
1256
    
1257
    throw new Exception("Unsupported LDAP type: " . $ldapHandler['type']);
1258
}
1259
1260
/**
1261
 * Permits to update the user's AD groups with mapping roles
1262
 *
1263
 * @param string $username
1264
 * @param array $userInfo
1265
 * @param array $groups
1266
 * @param array $SETTINGS
1267
 * @return void
1268
 */
1269
function handleUserADGroups(string $username, array $userInfo, array $groups, array $SETTINGS): void
1270
{
1271
    if (isset($SETTINGS['enable_ad_users_with_ad_groups']) === true && (int) $SETTINGS['enable_ad_users_with_ad_groups'] === 1) {
1272
        // Get user groups from AD
1273
        $user_ad_groups = [];
1274
        foreach($groups as $group) {
1275
            //print_r($group);
1276
            // get relation role id for AD group
1277
            $role = DB::queryFirstRow(
1278
                'SELECT lgr.role_id
1279
                FROM ' . prefixTable('ldap_groups_roles') . ' AS lgr
1280
                WHERE lgr.ldap_group_id = %s',
1281
                $group
1282
            );
1283
            if (DB::count() > 0) {
1284
                array_push($user_ad_groups, $role['role_id']); 
1285
            }
1286
        }
1287
        
1288
        // save
1289
        if (count($user_ad_groups) > 0) {
1290
            $user_ad_groups = implode(';', $user_ad_groups);
1291
            DB::update(
1292
                prefixTable('users'),
1293
                [
1294
                    'roles_from_ad_groups' => $user_ad_groups,
1295
                ],
1296
                'id = %i',
1297
                $userInfo['id']
1298
            );
1299
1300
            $userInfo['roles_from_ad_groups'] = $user_ad_groups;
1301
        } else {
1302
            DB::update(
1303
                prefixTable('users'),
1304
                [
1305
                    'roles_from_ad_groups' => null,
1306
                ],
1307
                'id = %i',
1308
                $userInfo['id']
1309
            );
1310
1311
            $userInfo['roles_from_ad_groups'] = [];
1312
        }
1313
    } else {
1314
        // Delete all user's AD groups
1315
        DB::update(
1316
            prefixTable('users'),
1317
            [
1318
                'roles_from_ad_groups' => null,
1319
            ],
1320
            'id = %i',
1321
            $userInfo['id']
1322
        );
1323
    }
1324
}
1325
1326
/**
1327
 * Permits to finalize the authentication process.
1328
 *
1329
 * @param array $userInfo
1330
 * @param string $passwordClear
1331
 * @param array $SETTINGS
1332
 */
1333
function finalizeAuthentication(
1334
    array $userInfo,
1335
    string $passwordClear,
1336
    array $SETTINGS
1337
): void
1338
{
1339
    $passwordManager = new PasswordManager();
1340
    
1341
    // Migrate password if needed
1342
    $hashedPassword = $passwordManager->migratePassword(
1343
        $userInfo['pw'],
1344
        $passwordClear,
1345
        (int) $userInfo['id']
1346
    );
1347
    
1348
    if (empty($userInfo['pw']) === true || $userInfo['special'] === 'user_added_from_ldap') {
1349
        // 2 cases are managed here:
1350
        // Case where user has never been connected then erase current pwd with the ldap's one
1351
        // Case where user has been added from LDAP and never being connected to TP
1352
        DB::update(
1353
            prefixTable('users'),
1354
            [
1355
                'pw' => $passwordManager->hashPassword($passwordClear),
1356
            ],
1357
            'id = %i',
1358
            $userInfo['id']
1359
        );
1360
    } elseif ($passwordManager->verifyPassword($hashedPassword, $passwordClear) === false) {
1361
        // Case where user is auth by LDAP but his password in Teampass is not synchronized
1362
        // For example when user has changed his password in AD.
1363
        // So we need to update it in Teampass and ask for private key re-encryption
1364
        DB::update(
1365
            prefixTable('users'),
1366
            [
1367
                'pw' => $passwordManager->hashPassword($passwordClear),
1368
            ],
1369
            'id = %i',
1370
            $userInfo['id']
1371
        );
1372
    }
1373
}
1374
1375
/**
1376
 * Undocumented function.
1377
 *
1378
 * @param string $username      User name
1379
 * @param string $passwordClear User password in clear
1380
 * @param array $retLDAP       Received data from LDAP
1381
 * @param array $SETTINGS      Teampass settings
1382
 *
1383
 * @return array
1384
 */
1385
function externalAdCreateUser(
1386
    string $login,
1387
    string $passwordClear,
1388
    string $userEmail,
1389
    string $userName,
1390
    string $userLastname,
1391
    string $authType,
1392
    array $userGroups,
1393
    array $SETTINGS
1394
): array
1395
{
1396
    // Generate user keys pair
1397
    $userKeys = generateUserKeys($passwordClear);
1398
1399
    // Create password hash
1400
    $passwordManager = new PasswordManager();
1401
    $hashedPassword = $passwordManager->hashPassword($passwordClear);
1402
    
1403
    // If any groups provided, add user to them
1404
    if (count($userGroups) > 0) {
1405
        $groupIds = [];
1406
        foreach ($userGroups as $group) {
1407
            // Check if exists in DB
1408
            $groupData = DB::queryFirstRow(
1409
                'SELECT id
1410
                FROM ' . prefixTable('roles_title') . '
1411
                WHERE title = %s',
1412
                $group["displayName"]
1413
            );
1414
1415
            if (DB::count() > 0) {
1416
                array_push($groupIds, $groupData['id']);
1417
            }
1418
        }
1419
        $userGroups = implode(';', $groupIds);
1420
    } else {
1421
        $userGroups = '';
1422
    }
1423
1424
    // Insert user in DB
1425
    DB::insert(
1426
        prefixTable('users'),
1427
        [
1428
            'login' => (string) $login,
1429
            'pw' => (string) $hashedPassword,
1430
            'email' => (string) $userEmail,
1431
            'name' => (string) $userName,
1432
            'lastname' => (string) $userLastname,
1433
            'admin' => '0',
1434
            'gestionnaire' => '0',
1435
            'can_manage_all_users' => '0',
1436
            'personal_folder' => $SETTINGS['enable_pf_feature'] === '1' ? '1' : '0',
1437
            'groupes_interdits' => '',
1438
            'groupes_visibles' => '',
1439
            'fonction_id' => $userGroups,
1440
            'last_pw_change' => (int) time(),
1441
            'user_language' => (string) $SETTINGS['default_language'],
1442
            'encrypted_psk' => '',
1443
            'isAdministratedByRole' => isset($SETTINGS['ldap_new_user_is_administrated_by']) === true && empty($SETTINGS['ldap_new_user_is_administrated_by']) === false ? $SETTINGS['ldap_new_user_is_administrated_by'] : 0,
1444
            'public_key' => $userKeys['public_key'],
1445
            'private_key' => $userKeys['private_key'],
1446
            'special' => 'none',
1447
            'auth_type' => $authType,
1448
            'otp_provided' => '1',
1449
            'is_ready_for_usage' => '0',
1450
        ]
1451
    );
1452
    $newUserId = DB::insertId();
1453
1454
    // Create the API key
1455
    DB::insert(
1456
        prefixTable('api'),
1457
        array(
1458
            'type' => 'user',
1459
            'user_id' => $newUserId,
1460
            'value' => encryptUserObjectKey(base64_encode(base64_encode(uniqidReal(39))), $userKeys['public_key']),
1461
            'timestamp' => time(),
1462
            'allowed_to_read' => 1,
1463
            'allowed_folders' => '',
1464
            'enabled' => 0,
1465
        )
1466
    );
1467
1468
    // Create personnal folder
1469
    if (isKeyExistingAndEqual('enable_pf_feature', 1, $SETTINGS) === true) {
1470
        DB::insert(
1471
            prefixTable('nested_tree'),
1472
            [
1473
                'parent_id' => '0',
1474
                'title' => $newUserId,
1475
                'bloquer_creation' => '0',
1476
                'bloquer_modification' => '0',
1477
                'personal_folder' => '1',
1478
                'categories' => '',
1479
            ]
1480
        );
1481
        // Rebuild tree
1482
        $tree = new NestedTree(prefixTable('nested_tree'), 'id', 'parent_id', 'title');
1483
        $tree->rebuild();
1484
    }
1485
1486
1487
    return [
1488
        'error' => false,
1489
        'message' => '',
1490
        'proceedIdentification' => true,
1491
        'user_initial_creation_through_external_ad' => true,
1492
        'id' => $newUserId,
1493
        'oauth2_login_ongoing' => true,
1494
    ];
1495
}
1496
1497
/**
1498
 * Undocumented function.
1499
 *
1500
 * @param string                $username     Username
1501
 * @param array                 $userInfo     Result of query
1502
 * @param string|array|resource $dataReceived DataReceived
1503
 * @param array                 $SETTINGS     Teampass settings
1504
 *
1505
 * @return array
1506
 */
1507
function googleMFACheck(string $username, array $userInfo, $dataReceived, array $SETTINGS): array
1508
{
1509
    $session = SessionManager::getSession();    
1510
    $lang = new Language($session->get('user-language') ?? 'english');
1511
1512
    if (
1513
        isset($dataReceived['GACode']) === true
1514
        && empty($dataReceived['GACode']) === false
1515
    ) {
1516
        $sessionAdmin = $session->get('user-admin');
1517
        $sessionUrl = $session->get('user-initial_url');
1518
        $sessionPwdAttempts = $session->get('pwd_attempts');
1519
        // create new instance
1520
        $tfa = new TwoFactorAuth($SETTINGS['ga_website_name']);
1521
        // Init
1522
        $firstTime = [];
1523
        // now check if it is the 1st time the user is using 2FA
1524
        if ($userInfo['ga_temporary_code'] !== 'none' && $userInfo['ga_temporary_code'] !== 'done') {
1525
            if ($userInfo['ga_temporary_code'] !== $dataReceived['GACode']) {
1526
                return [
1527
                    'error' => true,
1528
                    'message' => $lang->get('ga_bad_code'),
1529
                    'proceedIdentification' => false,
1530
                    'ga_bad_code' => true,
1531
                    'firstTime' => $firstTime,
1532
                ];
1533
            }
1534
1535
            // If first time with MFA code
1536
            $proceedIdentification = false;
1537
            
1538
            // generate new QR
1539
            $new_2fa_qr = $tfa->getQRCodeImageAsDataUri(
1540
                'Teampass - ' . $username,
1541
                $userInfo['ga']
1542
            );
1543
            // clear temporary code from DB
1544
            DB::update(
1545
                prefixTable('users'),
1546
                [
1547
                    'ga_temporary_code' => 'done',
1548
                ],
1549
                'id=%i',
1550
                $userInfo['id']
1551
            );
1552
            $firstTime = [
1553
                'value' => '<img src="' . $new_2fa_qr . '">',
1554
                'user_admin' => isset($sessionAdmin) ? (int) $sessionAdmin : '',
1555
                'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
1556
                'pwd_attempts' => (int) $sessionPwdAttempts,
1557
                'message' => $lang->get('ga_flash_qr_and_login'),
1558
                'mfaStatus' => 'ga_temporary_code_correct',
1559
            ];
1560
        } else {
1561
            // verify the user GA code
1562
            if ($tfa->verifyCode($userInfo['ga'], $dataReceived['GACode'])) {
1563
                $proceedIdentification = true;
1564
            } else {
1565
                return [
1566
                    'error' => true,
1567
                    'message' => $lang->get('ga_bad_code'),
1568
                    'proceedIdentification' => false,
1569
                    'ga_bad_code' => true,
1570
                    'firstTime' => $firstTime,
1571
                ];
1572
            }
1573
        }
1574
    } else {
1575
        return [
1576
            'error' => true,
1577
            'message' => $lang->get('ga_bad_code'),
1578
            'proceedIdentification' => false,
1579
            'ga_bad_code' => true,
1580
            'firstTime' => [],
1581
        ];
1582
    }
1583
1584
    return [
1585
        'error' => false,
1586
        'message' => '',
1587
        'proceedIdentification' => $proceedIdentification,
1588
        'firstTime' => $firstTime,
1589
    ];
1590
}
1591
1592
1593
/**
1594
 * Perform DUO checks
1595
 *
1596
 * @param string $username
1597
 * @param string|array|resource $dataReceived
1598
 * @param array $SETTINGS
1599
 * @return array
1600
 */
1601
function duoMFACheck(
1602
    string $username,
1603
    $dataReceived,
1604
    array $SETTINGS
1605
): array
1606
{
1607
    $session = SessionManager::getSession();
1608
    $lang = new Language($session->get('user-language') ?? 'english');
1609
1610
    $sessionPwdAttempts = $session->get('pwd_attempts');
1611
    $saved_state = null !== $session->get('user-duo_state') ? $session->get('user-duo_state') : '';
1612
    $duo_status = null !== $session->get('user-duo_status') ? $session->get('user-duo_status') : '';
1613
1614
    // Ensure state and login are set
1615
    if (
1616
        (empty($saved_state) || empty($dataReceived['login']) || !isset($dataReceived['duo_state']) || empty($dataReceived['duo_state']))
1617
        && $duo_status === 'IN_PROGRESS'
1618
        && $dataReceived['duo_status'] !== 'start_duo_auth'
1619
    ) {
1620
        return [
1621
            'error' => true,
1622
            'message' => $lang->get('duo_no_data'),
1623
            'pwd_attempts' => (int) $sessionPwdAttempts,
1624
            'proceedIdentification' => false,
1625
        ];
1626
    }
1627
1628
    // Ensure state matches from initial request
1629
    if ($duo_status === 'IN_PROGRESS' && $dataReceived['duo_state'] !== $saved_state) {
1630
        $session->set('user-duo_state', '');
1631
        $session->set('user-duo_status', '');
1632
1633
        // We did not received a proper Duo state
1634
        return [
1635
            'error' => true,
1636
            'message' => $lang->get('duo_error_state'),
1637
            'pwd_attempts' => (int) $sessionPwdAttempts,
1638
            'proceedIdentification' => false,
1639
        ];
1640
    }
1641
1642
    return [
1643
        'error' => false,
1644
        'pwd_attempts' => (int) $sessionPwdAttempts,
1645
        'saved_state' => $saved_state,
1646
        'duo_status' => $duo_status,
1647
    ];
1648
}
1649
1650
1651
/**
1652
 * Create the redirect URL or check if the DUO Universal prompt was completed successfully.
1653
 *
1654
 * @param string                $username               Username
1655
 * @param string|array|resource $dataReceived           DataReceived
1656
 * @param array                 $sessionPwdAttempts     Nb of pwd attempts
1657
 * @param array                 $saved_state            Saved state
1658
 * @param array                 $duo_status             Duo status
1659
 * @param array                 $SETTINGS               Teampass settings
1660
 *
1661
 * @return array
1662
 */
1663
function duoMFAPerform(
1664
    string $username,
1665
    $dataReceived,
1666
    int $sessionPwdAttempts,
1667
    string $saved_state,
1668
    string $duo_status,
1669
    array $SETTINGS
1670
): array
1671
{
1672
    $session = SessionManager::getSession();
1673
    $lang = new Language($session->get('user-language') ?? 'english');
1674
1675
    try {
1676
        $duo_client = new Client(
1677
            $SETTINGS['duo_ikey'],
1678
            $SETTINGS['duo_skey'],
1679
            $SETTINGS['duo_host'],
1680
            $SETTINGS['cpassman_url'].'/'.DUO_CALLBACK
1681
        );
1682
    } catch (DuoException $e) {
1683
        return [
1684
            'error' => true,
1685
            'message' => $lang->get('duo_config_error'),
1686
            'debug_message' => $e->getMessage(),
1687
            'pwd_attempts' => (int) $sessionPwdAttempts,
1688
            'proceedIdentification' => false,
1689
        ];
1690
    }
1691
        
1692
    try {
1693
        $duo_error = $lang->get('duo_error_secure');
1694
        $duo_failmode = "none";
1695
        $duo_client->healthCheck();
1696
    } catch (DuoException $e) {
1697
        //Not implemented Duo Failmode in case the Duo services are not available
1698
        /*if ($SETTINGS['duo_failmode'] == "safe") {
1699
            # If we're failing open, errors in 2FA still allow for success
1700
            $duo_error = $lang->get('duo_error_failopen');
1701
            $duo_failmode = "safe";
1702
        } else {
1703
            # Duo has failed and is unavailable, redirect user to the login page
1704
            $duo_error = $lang->get('duo_error_secure');
1705
            $duo_failmode = "secure";
1706
        }*/
1707
        return [
1708
            'error' => true,
1709
            'message' => $duo_error . $lang->get('duo_error_check_config'),
1710
            'pwd_attempts' => (int) $sessionPwdAttempts,
1711
            'debug_message' => $e->getMessage(),
1712
            'proceedIdentification' => false,
1713
        ];
1714
    }
1715
    
1716
    // Check if no one played with the javascript
1717
    if ($duo_status !== 'IN_PROGRESS' && $dataReceived['duo_status'] === 'start_duo_auth') {
1718
        # Create the Duo URL to send the user to
1719
        try {
1720
            $duo_state = $duo_client->generateState();
1721
            $duo_redirect_url = $duo_client->createAuthUrl($username, $duo_state);
1722
        } catch (DuoException $e) {
1723
            return [
1724
                'error' => true,
1725
                'message' => $duo_error . $lang->get('duo_error_url'),
1726
                'pwd_attempts' => (int) $sessionPwdAttempts,
1727
                'debug_message' => $e->getMessage(),
1728
                'proceedIdentification' => false,
1729
            ];
1730
        }
1731
        
1732
        // Somethimes Duo return success but fail to return a URL, double check if the URL has been created
1733
        if (!empty($duo_redirect_url) && filter_var($duo_redirect_url,FILTER_SANITIZE_URL)) {
1734
            // Since Duo Universal requires a redirect, let's store some info when the user get's back after completing the Duo prompt
1735
            $key = hash('sha256', $duo_state);
1736
            $iv = substr(hash('sha256', $duo_state), 0, 16);
1737
            $duo_data = serialize([
1738
                'duo_login' => $username,
1739
                'duo_pwd' => $dataReceived['pw'],
1740
            ]);
1741
            $duo_data_enc = openssl_encrypt($duo_data, 'AES-256-CBC', $key, 0, $iv);
1742
            $session->set('user-duo_state', $duo_state);
1743
            $session->set('user-duo_data', base64_encode($duo_data_enc));
1744
            $session->set('user-duo_status', 'IN_PROGRESS');
1745
            $session->set('user-login', $username);
1746
            
1747
            // If we got here we can reset the password attempts
1748
            $session->set('pwd_attempts', 0);
1749
            
1750
            return [
1751
                'error' => false,
1752
                'message' => '',
1753
                'proceedIdentification' => false,
1754
                'duo_url_ready' => true,
1755
                'duo_redirect_url' => $duo_redirect_url,
1756
                'duo_failmode' => $duo_failmode,
1757
            ];
1758
        } else {
1759
            return [
1760
                'error' => true,
1761
                'message' => $duo_error . $lang->get('duo_error_url'),
1762
                'pwd_attempts' => (int) $sessionPwdAttempts,
1763
                'proceedIdentification' => false,
1764
            ];
1765
        }
1766
    } elseif ($duo_status === 'IN_PROGRESS' && $dataReceived['duo_code'] !== '') {
1767
        try {
1768
            // Check if the Duo code received is valid
1769
            $decoded_token = $duo_client->exchangeAuthorizationCodeFor2FAResult($dataReceived['duo_code'], $username);
1770
        } catch (DuoException $e) {
1771
            return [
1772
                'error' => true,
1773
                'message' => $lang->get('duo_error_decoding'),
1774
                'pwd_attempts' => (int) $sessionPwdAttempts,
1775
                'debug_message' => $e->getMessage(),
1776
                'proceedIdentification' => false,
1777
            ];
1778
        }
1779
        // return the response (which should be the user name)
1780
        if ($decoded_token['preferred_username'] === $username) {
1781
            $session->set('user-duo_status', 'COMPLET');
1782
            $session->set('user-duo_state','');
1783
            $session->set('user-duo_data','');
1784
            $session->set('user-login', $username);
1785
1786
            return [
1787
                'error' => false,
1788
                'message' => '',
1789
                'proceedIdentification' => true,
1790
                'authenticated_username' => $decoded_token['preferred_username']
1791
            ];
1792
        } else {
1793
            // Something wrong, username from the original Duo request is different than the one received now
1794
            $session->set('user-duo_status','');
1795
            $session->set('user-duo_state','');
1796
            $session->set('user-duo_data','');
1797
1798
            return [
1799
                'error' => true,
1800
                'message' => $lang->get('duo_login_mismatch'),
1801
                'pwd_attempts' => (int) $sessionPwdAttempts,
1802
                'proceedIdentification' => false,
1803
            ];
1804
        }
1805
    }
1806
    // If we are here something wrong
1807
    $session->set('user-duo_status','');
1808
    $session->set('user-duo_state','');
1809
    $session->set('user-duo_data','');
1810
    return [
1811
        'error' => true,
1812
        'message' => $lang->get('duo_login_mismatch'),
1813
        'pwd_attempts' => (int) $sessionPwdAttempts,
1814
        'proceedIdentification' => false,
1815
    ];
1816
}
1817
1818
/**
1819
 * Undocumented function.
1820
 *
1821
 * @param string                $passwordClear Password in clear
1822
 * @param array|string          $userInfo      Array of user data
1823
 *
1824
 * @return bool
1825
 */
1826
function checkCredentials($passwordClear, $userInfo): bool
1827
{
1828
    $passwordManager = new PasswordManager();
1829
    // Migrate password if needed
1830
    $passwordManager->migratePassword(
1831
        $userInfo['pw'],
1832
        $passwordClear,
1833
        (int) $userInfo['id']
1834
    );
1835
1836
    if ($passwordManager->verifyPassword($userInfo['pw'], $passwordClear) === false) {
1837
        // password is not correct
1838
        return false;
1839
    }
1840
1841
    return true;
1842
}
1843
1844
/**
1845
 * Undocumented function.
1846
 *
1847
 * @param bool   $enabled text1
1848
 * @param string $dbgFile text2
1849
 * @param string $text    text3
1850
 */
1851
function debugIdentify(bool $enabled, string $dbgFile, string $text): void
1852
{
1853
    if ($enabled === true) {
1854
        $fp = fopen($dbgFile, 'a');
1855
        if ($fp !== false) {
1856
            fwrite(
1857
                $fp,
1858
                $text
1859
            );
1860
        }
1861
    }
1862
}
1863
1864
1865
1866
function identifyGetUserCredentials(
1867
    array $SETTINGS,
1868
    string $serverPHPAuthUser,
1869
    string $serverPHPAuthPw,
1870
    string $userPassword,
1871
    string $userLogin
1872
): array
1873
{
1874
    if ((int) $SETTINGS['enable_http_request_login'] === 1
1875
        && $serverPHPAuthUser !== null
1876
        && (int) $SETTINGS['maintenance_mode'] === 1
1877
    ) {
1878
        if (strpos($serverPHPAuthUser, '@') !== false) {
1879
            return [
1880
                'username' => explode('@', $serverPHPAuthUser)[0],
1881
                'passwordClear' => $serverPHPAuthPw
1882
            ];
1883
        }
1884
        
1885
        if (strpos($serverPHPAuthUser, '\\') !== false) {
1886
            return [
1887
                'username' => explode('\\', $serverPHPAuthUser)[1],
1888
                'passwordClear' => $serverPHPAuthPw
1889
            ];
1890
        }
1891
1892
        return [
1893
            'username' => $serverPHPAuthPw,
1894
            'passwordClear' => $serverPHPAuthPw
1895
        ];
1896
    }
1897
    
1898
    return [
1899
        'username' => $userLogin,
1900
        'passwordClear' => $userPassword
1901
    ];
1902
}
1903
1904
1905
class initialChecks {
1906
    // Properties
1907
    public $login;
1908
1909
    /**
1910
     * Check if the user or his IP address is blocked due to a high number of
1911
     * failed attempts.
1912
     * 
1913
     * @param string $username - The login tried to login.
1914
     * @param string $ip - The remote address of the user.
1915
     */
1916
    public function isTooManyPasswordAttempts($username, $ip) {
1917
1918
        // Check for existing lock
1919
        $unlock_at = DB::queryFirstField(
1920
            'SELECT MAX(unlock_at)
1921
             FROM ' . prefixTable('auth_failures') . '
1922
             WHERE unlock_at > %s
1923
             AND ((source = %s AND value = %s) OR (source = %s AND value = %s))',
1924
            date('Y-m-d H:i:s', time()),
1925
            'login',
1926
            $username,
1927
            'remote_ip',
1928
            $ip
1929
        );
1930
1931
        // Account or remote address locked
1932
        if ($unlock_at) {
1933
            throw new Exception((string) $unlock_at);
1934
        }
1935
    }
1936
1937
    public function getUserInfo($login, $enable_ad_user_auto_creation, $oauth2_enabled) {
1938
        $session = SessionManager::getSession();
1939
    
1940
        // Get user info from DB
1941
        $data = DB::queryFirstRow(
1942
            'SELECT u.*, a.value AS api_key
1943
            FROM ' . prefixTable('users') . ' AS u
1944
            LEFT JOIN ' . prefixTable('api') . ' AS a ON (u.id = a.user_id)
1945
            WHERE login = %s AND deleted_at IS NULL',
1946
            $login
1947
        );
1948
    
1949
        // User doesn't exist then return error
1950
        // Except if user creation from LDAP is enabled
1951
        if (
1952
            DB::count() === 0
1953
            && !filter_var($enable_ad_user_auto_creation, FILTER_VALIDATE_BOOLEAN) 
1954
            && !filter_var($oauth2_enabled, FILTER_VALIDATE_BOOLEAN)
1955
        ) {
1956
            throw new Exception("error");
1957
        }
1958
    
1959
        // We cannot create a user with LDAP if the OAuth2 login is ongoing
1960
        $oauth2LoginOngoing = $session->get('userOauth2Info')['oauth2LoginOngoing'] ?? false;
1961
        $oauth2LoginOngoing = filter_var($oauth2LoginOngoing, FILTER_VALIDATE_BOOLEAN) ?? false;
1962
    
1963
        $data['oauth2_login_ongoing'] = $oauth2LoginOngoing;
1964
        $data['ldap_user_to_be_created'] = (
1965
            filter_var($enable_ad_user_auto_creation, FILTER_VALIDATE_BOOLEAN) &&
1966
            DB::count() === 0 &&
1967
            !$oauth2LoginOngoing
1968
        );
1969
        $data['oauth2_user_to_be_created'] = (
1970
            filter_var($oauth2_enabled, FILTER_VALIDATE_BOOLEAN) &&
1971
            DB::count() === 0 &&
1972
            $oauth2LoginOngoing
1973
        );
1974
    
1975
        return $data;
1976
    }
1977
1978
    public function isMaintenanceModeEnabled($maintenance_mode, $user_admin) {
1979
        if ((int) $maintenance_mode === 1 && (int) $user_admin === 0) {
1980
            throw new Exception(
1981
                "error" 
1982
            );
1983
        }
1984
    }
1985
1986
    public function is2faCodeRequired(
1987
        $yubico,
1988
        $ga,
1989
        $duo,
1990
        $admin,
1991
        $adminMfaRequired,
1992
        $mfa,
1993
        $userMfaSelection,
1994
        $userMfaEnabled
1995
    ) {
1996
        if (
1997
            (empty($userMfaSelection) === true &&
1998
            isOneVarOfArrayEqualToValue(
1999
                [
2000
                    (int) $yubico,
2001
                    (int) $ga,
2002
                    (int) $duo
2003
                ],
2004
                1
2005
            ) === true)
2006
            && (((int) $admin !== 1 && $userMfaEnabled === true) || ((int) $adminMfaRequired === 1 && (int) $admin === 1))
2007
            && $mfa === true
2008
        ) {
2009
            throw new Exception(
2010
                "error" 
2011
            );
2012
        }
2013
    }
2014
2015
    public function isInstallFolderPresent($admin, $install_folder) {
2016
        if ((int) $admin === 1 && is_dir($install_folder) === true) {
2017
            throw new Exception(
2018
                "error" 
2019
            );
2020
        }
2021
    }
2022
}
2023
2024
2025
/**
2026
 * Permit to get info about user before auth step
2027
 *
2028
 * @param array $SETTINGS
2029
 * @param integer $sessionPwdAttempts
2030
 * @param string $username
2031
 * @param integer $sessionAdmin
2032
 * @param string $sessionUrl
2033
 * @param string $user2faSelection
2034
 * @param boolean $oauth2Token
2035
 * @return array
2036
 */
2037
function identifyDoInitialChecks(
2038
    $SETTINGS,
2039
    int $sessionPwdAttempts,
2040
    string $username,
2041
    int $sessionAdmin,
2042
    string $sessionUrl,
2043
    string $user2faSelection
2044
): array
2045
{
2046
    $session = SessionManager::getSession();
2047
    $checks = new initialChecks();
2048
    $enableAdUserAutoCreation = $SETTINGS['enable_ad_user_auto_creation'] ?? false;
2049
    $oauth2Enabled = $SETTINGS['oauth2_enabled'] ?? false;
2050
    $lang = new Language($session->get('user-language') ?? 'english');
2051
2052
    // Brute force management
2053
    try {
2054
        $checks->isTooManyPasswordAttempts($username, getClientIpServer());
2055
    } catch (Exception $e) {
2056
        $session->set('userOauth2Info', '');
2057
        logEvents($SETTINGS, 'failed_auth', 'user_not_exists', '', stripslashes($username), stripslashes($username));
2058
        return [
2059
            'error' => true,
2060
            'skip_anti_bruteforce' => true,
2061
            'array' => [
2062
                'value' => 'bruteforce_wait',
2063
                'error' => true,
2064
                'message' => $lang->get('bruteforce_wait') . (string) $e->getMessage(),
2065
            ]
2066
        ];
2067
    }
2068
2069
    // Check if user exists
2070
    try {
2071
        $userInfo = $checks->getUserInfo($username, $enableAdUserAutoCreation, $oauth2Enabled);
2072
    } catch (Exception $e) {
2073
        logEvents($SETTINGS, 'failed_auth', 'user_not_exists', '', stripslashes($username), stripslashes($username));
2074
        return [
2075
            'error' => true,
2076
            'array' => [
2077
                'error' => true,
2078
                'message' => $lang->get('error_bad_credentials'),
2079
            ]
2080
        ];
2081
    }
2082
2083
    // Manage Maintenance mode
2084
    try {
2085
        $checks->isMaintenanceModeEnabled(
2086
            $SETTINGS['maintenance_mode'],
2087
            $userInfo['admin']
2088
        );
2089
    } catch (Exception $e) {
2090
        return [
2091
            'error' => true,
2092
            'skip_anti_bruteforce' => true,
2093
            'array' => [
2094
                'value' => '',
2095
                'error' => 'maintenance_mode_enabled',
2096
                'message' => '',
2097
            ]
2098
        ];
2099
    }
2100
    
2101
    // user should use MFA?
2102
    $userInfo['mfa_auth_requested_roles'] = mfa_auth_requested_roles(
2103
        (string) $userInfo['fonction_id'],
2104
        is_null($SETTINGS['mfa_for_roles']) === true ? '' : (string) $SETTINGS['mfa_for_roles']
2105
    );
2106
2107
    // Check if 2FA code is requested
2108
    try {
2109
        $checks->is2faCodeRequired(
2110
            $SETTINGS['yubico_authentication'],
2111
            $SETTINGS['google_authentication'],
2112
            $SETTINGS['duo'],
2113
            $userInfo['admin'],
2114
            $SETTINGS['admin_2fa_required'],
2115
            $userInfo['mfa_auth_requested_roles'],
2116
            $user2faSelection,
2117
            $userInfo['mfa_enabled']
2118
        );
2119
    } catch (Exception $e) {
2120
        return [
2121
            'error' => true,
2122
            'array' => [
2123
                'value' => '2fa_not_set',
2124
                'user_admin' => (int) $sessionAdmin,
2125
                'initial_url' => $sessionUrl,
2126
                'pwd_attempts' => (int) $sessionPwdAttempts,
2127
                'error' => '2fa_not_set',
2128
                'message' => $lang->get('select_valid_2fa_credentials'),
2129
            ]
2130
        ];
2131
    }
2132
    // If admin user then check if folder install exists
2133
    // if yes then refuse connection
2134
    try {
2135
        $checks->isInstallFolderPresent(
2136
            $userInfo['admin'],
2137
            '../install'
2138
        );
2139
    } catch (Exception $e) {
2140
        return [
2141
            'error' => true,
2142
            'array' => [
2143
                'value' => '',
2144
                'user_admin' => $sessionAdmin,
2145
                'initial_url' => $sessionUrl,
2146
                'pwd_attempts' => (int) $sessionPwdAttempts,
2147
                'error' => true,
2148
                'message' => $lang->get('remove_install_folder'),
2149
            ]
2150
        ];
2151
    }
2152
2153
    // Return some usefull information about user
2154
    return [
2155
        'error' => false,
2156
        'user_mfa_mode' => $user2faSelection,
2157
        'userInfo' => $userInfo,
2158
    ];
2159
}
2160
2161
function identifyDoLDAPChecks(
2162
    $SETTINGS,
2163
    $userInfo,
2164
    string $username,
2165
    string $passwordClear,
2166
    int $sessionAdmin,
2167
    string $sessionUrl,
2168
    int $sessionPwdAttempts
2169
): array
2170
{
2171
    $session = SessionManager::getSession();
2172
    $lang = new Language($session->get('user-language') ?? 'english');
2173
2174
    // Prepare LDAP connection if set up
2175
    if ((int) $SETTINGS['ldap_mode'] === 1
2176
        && $username !== 'admin'
2177
        && ((string) $userInfo['auth_type'] === 'ldap' || $userInfo['ldap_user_to_be_created'] === true)
2178
    ) {
2179
        $retLDAP = authenticateThroughAD(
2180
            $username,
2181
            $userInfo,
2182
            $passwordClear,
2183
            $SETTINGS
2184
        );
2185
        if ($retLDAP['error'] === true) {
2186
            return [
2187
                'error' => true,
2188
                'array' => [
2189
                    'value' => '',
2190
                    'user_admin' => $sessionAdmin,
2191
                    'initial_url' => $sessionUrl,
2192
                    'pwd_attempts' => (int) $sessionPwdAttempts,
2193
                    'error' => true,
2194
                    'message' => $lang->get('error_bad_credentials'),
2195
                ]
2196
            ];
2197
        }
2198
        return [
2199
            'error' => false,
2200
            'retLDAP' => $retLDAP,
2201
            'ldapConnection' => true,
2202
            'userPasswordVerified' => true,
2203
        ];
2204
    }
2205
2206
    // return if no addmin
2207
    return [
2208
        'error' => false,
2209
        'retLDAP' => [],
2210
        'ldapConnection' => false,
2211
        'userPasswordVerified' => false,
2212
    ];
2213
}
2214
2215
2216
function shouldUserAuthWithOauth2(
2217
    array $SETTINGS,
2218
    array $userInfo,
2219
    string $username
2220
): array
2221
{
2222
    // Security issue without this return if an user auth_type == oauth2 and
2223
    // oauth2 disabled : we can login as a valid user by using hashUserId(username)
2224
    // as password in the login the form.
2225
    if ((int) $SETTINGS['oauth2_enabled'] !== 1 && filter_var($userInfo['oauth2_login_ongoing'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === true) {
2226
        return [
2227
            'error' => true,
2228
            'message' => 'user_not_allowed_to_auth_to_teampass_app',
2229
            'oauth2Connection' => false,
2230
            'userPasswordVerified' => false,
2231
        ];
2232
    }
2233
2234
    // Prepare Oauth2 connection if set up
2235
    if ($username !== 'admin') {
2236
        // User has started to auth with oauth2
2237
        if ((bool) $userInfo['oauth2_login_ongoing'] === true) {
2238
            // Case where user exists in Teampass password login type
2239
            if ((string) $userInfo['auth_type'] === 'ldap' || (string) $userInfo['auth_type'] === 'local') {
2240
                // Update user in database:
2241
                DB::update(
2242
                    prefixTable('users'),
2243
                    array(
2244
                        'special' => 'recrypt-private-key',
2245
                        'auth_type' => 'oauth2',
2246
                    ),
2247
                    'id = %i',
2248
                    $userInfo['id']
2249
                );
2250
                // Update session auth type
2251
                $session = SessionManager::getSession();
2252
                $session->set('user-auth_type', 'oauth2');
2253
                // Accept login request
2254
                return [
2255
                    'error' => false,
2256
                    'message' => '',
2257
                    'oauth2Connection' => true,
2258
                    'userPasswordVerified' => true,
2259
                ];
2260
            } elseif ((string) $userInfo['auth_type'] === 'oauth2' || (bool) $userInfo['oauth2_login_ongoing'] === true) {
2261
                // OAuth2 login request on OAuth2 user account.
2262
                return [
2263
                    'error' => false,
2264
                    'message' => '',
2265
                    'oauth2Connection' => true,
2266
                    'userPasswordVerified' => true,
2267
                ];
2268
            } else {
2269
                // Case where auth_type is not managed
2270
                return [
2271
                    'error' => true,
2272
                    'message' => 'user_not_allowed_to_auth_to_teampass_app',
2273
                    'oauth2Connection' => false,
2274
                    'userPasswordVerified' => false,
2275
                ];
2276
            }
2277
        } else {
2278
            // User has started to auth the normal way
2279
            if ((string) $userInfo['auth_type'] === 'oauth2') {
2280
                // Case where user exists in Teampass but not allowed to auth with Oauth2
2281
                return [
2282
                    'error' => true,
2283
                    'message' => 'error_bad_credentials',
2284
                    'oauth2Connection' => false,
2285
                    'userPasswordVerified' => false,
2286
                ];
2287
            }
2288
        }
2289
    }
2290
2291
    // return if no addmin
2292
    return [
2293
        'error' => false,
2294
        'message' => '',
2295
        'oauth2Connection' => false,
2296
        'userPasswordVerified' => false,
2297
    ];
2298
}
2299
2300
function createOauth2User(
2301
    array $SETTINGS,
2302
    array $userInfo,
2303
    string $username,
2304
    string $passwordClear,
2305
    int $userLdapHasBeenCreated
2306
): array
2307
{
2308
    // Prepare creating the new oauth2 user in Teampass
2309
    if ((int) $SETTINGS['oauth2_enabled'] === 1
2310
        && $username !== 'admin'
2311
        && filter_var($userInfo['oauth2_user_to_be_created'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === true
2312
        && $userLdapHasBeenCreated !== 1
2313
    ) {
2314
        $session = SessionManager::getSession();
2315
        $lang = new Language($session->get('user-language') ?? 'english');
2316
        
2317
        // Create Oauth2 user if not exists and tasks enabled
2318
        $ret = externalAdCreateUser(
2319
            $username,
2320
            $passwordClear,
2321
            $userInfo['mail'],
2322
            is_null($userInfo['givenname']) ? (is_null($userInfo['givenName']) ? '' : $userInfo['givenName']) : $userInfo['givenname'],
2323
            is_null($userInfo['surname']) ? '' : $userInfo['surname'],
2324
            'oauth2',
2325
            is_null($userInfo['groups']) ? [] : $userInfo['groups'],
2326
            $SETTINGS
2327
        );
2328
        $userInfo = array_merge($userInfo, $ret);
2329
2330
        // prepapre background tasks for item keys generation  
2331
        handleUserKeys(
2332
            (int) $userInfo['id'],
2333
            (string) $passwordClear,
2334
            (int) (isset($SETTINGS['maximum_number_of_items_to_treat']) === true ? $SETTINGS['maximum_number_of_items_to_treat'] : NUMBER_ITEMS_IN_BATCH),
2335
            uniqidReal(20),
2336
            true,
2337
            true,
2338
            true,
2339
            false,
2340
            $lang->get('email_body_user_config_2'),
2341
        );
2342
2343
        // Complete $userInfo
2344
        $userInfo['has_been_created'] = 1;
2345
2346
        if (WIP === true) error_log("--- USER CREATED ---");
2347
2348
        return [
2349
            'error' => false,
2350
            'retExternalAD' => $userInfo,
2351
            'oauth2Connection' => true,
2352
            'userPasswordVerified' => true,
2353
        ];
2354
    
2355
    } elseif (isset($userInfo['id']) === true && empty($userInfo['id']) === false) {
2356
        // CHeck if user should use oauth2
2357
        $ret = shouldUserAuthWithOauth2(
2358
            $SETTINGS,
2359
            $userInfo,
2360
            $username
2361
        );
2362
        if ($ret['error'] === true) {
2363
            return [
2364
                'error' => true,
2365
                'message' => $ret['message'],
2366
            ];
2367
        }
2368
2369
        // login/password attempt on a local account:
2370
        // Return to avoid overwrite of user password that can allow a user
2371
        // to steal a local account.
2372
        if (!$ret['oauth2Connection'] || !$ret['userPasswordVerified']) {
2373
            return [
2374
                'error' => false,
2375
                'message' => $ret['message'],
2376
                'ldapConnection' => false,
2377
                'userPasswordVerified' => false,        
2378
            ];
2379
        }
2380
2381
        // Oauth2 user already exists and authenticated
2382
        if (WIP === true) error_log("--- USER AUTHENTICATED ---");
2383
        $userInfo['has_been_created'] = 0;
2384
2385
        $passwordManager = new PasswordManager();
2386
2387
        // Update user hash un database if needed
2388
        if (!$passwordManager->verifyPassword($userInfo['pw'], $passwordClear)) {
2389
            DB::update(
2390
                prefixTable('users'),
2391
                [
2392
                    'pw' => $passwordManager->hashPassword($passwordClear),
2393
                ],
2394
                'id = %i',
2395
                $userInfo['id']
2396
            );
2397
        }
2398
2399
        return [
2400
            'error' => false,
2401
            'retExternalAD' => $userInfo,
2402
            'oauth2Connection' => $ret['oauth2Connection'],
2403
            'userPasswordVerified' => $ret['userPasswordVerified'],
2404
        ];
2405
    }
2406
2407
    // return if no admin
2408
    return [
2409
        'error' => false,
2410
        'retLDAP' => [],
2411
        'ldapConnection' => false,
2412
        'userPasswordVerified' => false,
2413
    ];
2414
}
2415
2416
2417
function identifyDoMFAChecks(
2418
    $SETTINGS,
2419
    $userInfo,
2420
    $dataReceived,
2421
    $userInitialData,
2422
    string $username
2423
): array
2424
{
2425
    $session = SessionManager::getSession();
2426
    $lang = new Language($session->get('user-language') ?? 'english');
2427
    
2428
    switch ($userInitialData['user_mfa_mode']) {
2429
        case 'google':
2430
            $ret = googleMFACheck(
2431
                $username,
2432
                $userInfo,
2433
                $dataReceived,
2434
                $SETTINGS
2435
            );
2436
            if ($ret['error'] !== false) {
2437
                logEvents($SETTINGS, 'failed_auth', 'wrong_mfa_code', '', stripslashes($username), stripslashes($username));
2438
                return [
2439
                    'error' => true,
2440
                    'mfaData' => $ret,
2441
                    'mfaQRCodeInfos' => false,
2442
                ];
2443
            }
2444
2445
            return [
2446
                'error' => false,
2447
                'mfaData' => $ret['firstTime'],
2448
                'mfaQRCodeInfos' => $userInitialData['user_mfa_mode'] === 'google'
2449
                && count($ret['firstTime']) > 0 ? true : false,
2450
            ];
2451
        
2452
        case 'duo':
2453
            // Prepare Duo connection if set up
2454
            $checks = duoMFACheck(
2455
                $username,
2456
                $dataReceived,
2457
                $SETTINGS
2458
            );
2459
2460
            if ($checks['error'] === true) {
2461
                return [
2462
                    'error' => true,
2463
                    'mfaData' => $checks,
2464
                    'mfaQRCodeInfos' => false,
2465
                ];
2466
            }
2467
2468
            // If we are here
2469
            // Do DUO authentication
2470
            $ret = duoMFAPerform(
2471
                $username,
2472
                $dataReceived,
2473
                $checks['pwd_attempts'],
2474
                $checks['saved_state'],
2475
                $checks['duo_status'],
2476
                $SETTINGS
2477
            );
2478
2479
            if ($ret['error'] !== false) {
2480
                logEvents($SETTINGS, 'failed_auth', 'bad_duo_mfa', '', stripslashes($username), stripslashes($username));
2481
                $session->set('user-duo_status','');
2482
                $session->set('user-duo_state','');
2483
                $session->set('user-duo_data','');
2484
                return [
2485
                    'error' => true,
2486
                    'mfaData' => $ret,
2487
                    'mfaQRCodeInfos' => false,
2488
                ];
2489
            } else if ($ret['duo_url_ready'] === true){
2490
                return [
2491
                    'error' => false,
2492
                    'mfaData' => $ret,
2493
                    'duo_url_ready' => true,
2494
                    'mfaQRCodeInfos' => false,
2495
                ];
2496
            } else if ($ret['error'] === false) {
2497
                return [
2498
                    'error' => false,
2499
                    'mfaData' => $ret,
2500
                    'mfaQRCodeInfos' => false,
2501
                ];
2502
            }
2503
            break;
2504
        
2505
        default:
2506
            logEvents($SETTINGS, 'failed_auth', 'wrong_mfa_code', '', stripslashes($username), stripslashes($username));
2507
            return [
2508
                'error' => true,
2509
                'mfaData' => ['message' => $lang->get('wrong_mfa_code')],
2510
                'mfaQRCodeInfos' => false,
2511
            ];
2512
    }
2513
2514
    // If something went wrong, let's catch and return an error
2515
    logEvents($SETTINGS, 'failed_auth', 'wrong_mfa_code', '', stripslashes($username), stripslashes($username));
2516
    return [
2517
        'error' => true,
2518
        'mfaData' => ['message' => $lang->get('wrong_mfa_code')],
2519
        'mfaQRCodeInfos' => false,
2520
    ];
2521
}
2522
2523
function identifyDoAzureChecks(
2524
    array $SETTINGS,
2525
    $userInfo,
2526
    string $username
2527
): array
2528
{
2529
    $session = SessionManager::getSession();
2530
    $lang = new Language($session->get('user-language') ?? 'english');
2531
2532
    logEvents($SETTINGS, 'failed_auth', 'wrong_mfa_code', '', stripslashes($username), stripslashes($username));
2533
    return [
2534
        'error' => true,
2535
        'mfaData' => ['message' => $lang->get('wrong_mfa_code')],
2536
        'mfaQRCodeInfos' => false,
2537
    ];
2538
}
2539
2540
/**
2541
 * Add a failed authentication attempt to the database.
2542
 * If the number of failed attempts exceeds the limit, a lock is triggered.
2543
 * 
2544
 * @param string $source - The source of the failed attempt (login or remote_ip).
2545
 * @param string $value  - The value for this source (username or IP address).
2546
 * @param int    $limit  - The failure attempt limit after which the account/IP
2547
 *                         will be locked.
2548
 */
2549
function handleFailedAttempts($source, $value, $limit) {
2550
    // Count failed attempts from this source
2551
    $count = DB::queryFirstField(
2552
        'SELECT COUNT(*)
2553
        FROM ' . prefixTable('auth_failures') . '
2554
        WHERE source = %s AND value = %s',
2555
        $source,
2556
        $value
2557
    );
2558
2559
    // Add this attempt
2560
    $count++;
2561
2562
    // Calculate unlock time if number of attempts exceeds limit
2563
    $unlock_at = $count >= $limit
2564
        ? date('Y-m-d H:i:s', time() + (($count - $limit + 1) * 600))
2565
        : NULL;
2566
2567
    // Unlock account one time code
2568
    $unlock_code = ($count >= $limit && $source === 'login')
2569
        ? generateQuickPassword(30, false)
2570
        : NULL;
2571
2572
    // Insert the new failure into the database
2573
    DB::insert(
2574
        prefixTable('auth_failures'),
2575
        [
2576
            'source' => $source,
2577
            'value' => $value,
2578
            'unlock_at' => $unlock_at,
2579
            'unlock_code' => $unlock_code,
2580
        ]
2581
    );
2582
2583
    if ($unlock_at !== null && $source === 'login') {
2584
        $configManager = new ConfigManager();
2585
        $SETTINGS = $configManager->getAllSettings();
2586
        $lang = new Language($SETTINGS['default_language']);
2587
2588
        // Get user email
2589
        $userInfos = DB::queryFirstRow(
2590
            'SELECT email, name
2591
             FROM '.prefixTable('users').'
2592
             WHERE login = %s',
2593
             $value
2594
        );
2595
2596
        // No valid email address for user
2597
        if (!$userInfos || !filter_var($userInfos['email'], FILTER_VALIDATE_EMAIL))
2598
            return;
2599
2600
        $unlock_url = $SETTINGS['cpassman_url'].'/self-unlock.php?login='.$value.'&otp='.$unlock_code;
2601
2602
        sendMailToUser(
2603
            $userInfos['email'],
2604
            $lang->get('bruteforce_reset_mail_body'),
2605
            $lang->get('bruteforce_reset_mail_subject'),
2606
            [
2607
                '#name#' => $userInfos['name'],
2608
                '#reset_url#' => $unlock_url,
2609
                '#unlock_at#' => $unlock_at,
2610
            ],
2611
            true
2612
        );
2613
    }
2614
}
2615
2616
/**
2617
 * Add failed authentication attempts for both user login and IP address.
2618
 * This function will check the number of attempts for both the username and IP,
2619
 * and will trigger a lock if the number exceeds the defined limits.
2620
 * It also deletes logs older than 24 hours.
2621
 * 
2622
 * @param string $username - The username that was attempted to login.
2623
 * @param string $ip       - The IP address from which the login attempt was made.
2624
 */
2625
function addFailedAuthentication($username, $ip) {
2626
    $user_limit = 10;
2627
    $ip_limit = 30;
2628
2629
    // Remove old logs (more than 24 hours)
2630
    DB::delete(
2631
        prefixTable('auth_failures'),
2632
        'date < %s AND (unlock_at < %s OR unlock_at IS NULL)',
2633
        date('Y-m-d H:i:s', time() - (24 * 3600)),
2634
        date('Y-m-d H:i:s', time())
2635
    );
2636
2637
    // Add attempts in database
2638
    handleFailedAttempts('login', $username, $user_limit);
2639
    handleFailedAttempts('remote_ip', $ip, $ip_limit);
2640
}
2641