Passed
Pull Request — master (#4476)
by
unknown
06:39
created

identifyDoInitialChecks()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 121
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

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

How to fix   Long Method    Complexity   

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