-
-
Notifications
You must be signed in to change notification settings - Fork 551
/
Copy pathidentify.php
executable file
·2669 lines (2465 loc) · 96.1 KB
/
identify.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* Teampass - a collaborative passwords manager.
* ---
* This file is part of the TeamPass project.
*
* TeamPass is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* TeamPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Certain components of this file may be under different licenses. For
* details, see the `licenses` directory or individual file headers.
* ---
* @file identify.php
* @author Nils Laumaillé (nils@teampass.net)
* @copyright 2009-2024 Teampass.net
* @license GPL-3.0
* @see https://www.teampass.net
*/
use voku\helper\AntiXSS;
use EZimuel\PHPSecureSession;
use TeampassClasses\SessionManager\SessionManager;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use TeampassClasses\Language\Language;
use TeampassClasses\PerformChecks\PerformChecks;
use TeampassClasses\ConfigManager\ConfigManager;
use LdapRecord\Connection;
use LdapRecord\Container;
use LdapRecord\Auth\Events\Failed;
use TeampassClasses\NestedTree\NestedTree;
use TeampassClasses\PasswordManager\PasswordManager;
use Duo\DuoUniversal\Client;
use Duo\DuoUniversal\DuoException;
use RobThree\Auth\TwoFactorAuth;
use TeampassClasses\LdapExtra\LdapExtra;
use TeampassClasses\LdapExtra\OpenLdapExtra;
use TeampassClasses\LdapExtra\ActiveDirectoryExtra;
use TeampassClasses\OAuth2Controller\OAuth2Controller;
// Load functions
require_once 'main.functions.php';
// init
loadClasses('DB');
$session = SessionManager::getSession();
$request = SymfonyRequest::createFromGlobals();
$lang = new Language($session->get('user-language') ?? 'english');
// Load config
$configManager = new ConfigManager();
$SETTINGS = $configManager->getAllSettings();
// Do checks
// Instantiate the class with posted data
$checkUserAccess = new PerformChecks(
dataSanitizer(
[
'type' => $request->request->get('type', '') !== '' ? htmlspecialchars($request->request->get('type')) : '',
],
[
'type' => 'trim|escape',
],
),
[
'user_id' => returnIfSet($session->get('user-id'), null),
'user_key' => returnIfSet($session->get('key'), null),
'login' => isset($_POST['login']) === false ? null : $_POST['login'],
'oauth2' => returnIfSet($session->get('userOauth2Info'), null),
]
);
// Handle the case
echo $checkUserAccess->caseHandler();
if ($checkUserAccess->checkSession() === false) {
// Not allowed page
$session->set('system-error_code', ERR_NOT_ALLOWED);
echo json_encode([
'error' => true,
'message' => $lang->get('error_bad_credentials'),
]);
exit;
}
// Define Timezone
date_default_timezone_set(isset($SETTINGS['timezone']) === true ? $SETTINGS['timezone'] : 'UTC');
// Set header properties
header('Content-type: text/html; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
error_reporting(E_ERROR);
// --------------------------------- //
// Prepare POST variables
$post_type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$post_login = filter_input(INPUT_POST, 'login', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$post_data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_NO_ENCODE_QUOTES);
if ($post_type === 'identify_user') {
//--------
// NORMAL IDENTICATION STEP
//--------
// Ensure Complexity levels are translated
defineComplexity();
/**
* Permits to handle login attempts
*
* @param string $post_data
* @param array $SETTINGS
* @return bool|string
*/
function handleAuthAttempts($post_data, $SETTINGS): bool|string
{
$session = SessionManager::getSession();
$lang = new Language($session->get('user-language') ?? 'english');
$sessionPwdAttempts = $session->get('pwd_attempts');
$nextPossibleAttempts = (int) $session->get('next_possible_pwd_attempts');
// Check if the user is currently within the waiting period
if ($nextPossibleAttempts > 0 && time() < $nextPossibleAttempts) {
// Brute force wait
$remainingSeconds = $nextPossibleAttempts - time();
$errorResponse = prepareExchangedData([
'value' => 'bruteforce_wait',
'user_admin' => null !== $session->get('user-admin') ? (int) $session->get('user-admin') : 0,
'initial_url' => null !== $session->get('user-initial_url') ? $session->get('user-initial_url') : '',
'pwd_attempts' => 0,
'error' => true,
'message' => $lang->get('error_bad_credentials_more_than_3_times'),
'remaining_seconds' => $remainingSeconds,
], 'encode');
echo $errorResponse;
return false;
}
// Increment the counter of login attempts
$sessionPwdAttempts = ($sessionPwdAttempts === '') ? 1 : ++$sessionPwdAttempts;
$session->set('pwd_attempts', $sessionPwdAttempts);
// Check for brute force attempts
if ($sessionPwdAttempts <= 3) {
// Identify the user through Teampass process
identifyUser($post_data, $SETTINGS);
} else {
// Reset attempts and set waiting period on the fourth consecutive attempt
$session->set('pwd_attempts', 0);
if ($sessionPwdAttempts === 4) {
// On the fourth consecutive attempt, trigger the waiting period
$nextPossibleAttempts = time() + 10;
$session->set('next_possible_pwd_attempts', $nextPossibleAttempts);
// Send an error response indicating the waiting period
$errorResponse = prepareExchangedData([
'value' => 'bruteforce_wait',
'user_admin' => null !== $session->get('user-admin') ? (int) $session->get('user-admin') : 0,
'initial_url' => null !== $session->get('user-initial_url') ? $session->get('user-initial_url') : '',
'pwd_attempts' => 0,
'error' => true,
'message' => $lang->get('error_bad_credentials_more_than_3_times'),
'remaining_seconds' => 10,
], 'encode');
echo $errorResponse;
return false;
}
// Identify the user through Teampass process
identifyUser($post_data, $SETTINGS);
}
return true;
}
handleAuthAttempts($post_data, $SETTINGS);
// ---
// ---
// ---
} elseif ($post_type === 'get2FAMethods') {
//--------
// Get MFA methods
//--------
//
// Encrypt data to return
echo json_encode([
'ret' => prepareExchangedData(
[
'agses' => isKeyExistingAndEqual('agses_authentication_enabled', 1, $SETTINGS) === true ? true : false,
'google' => isKeyExistingAndEqual('google_authentication', 1, $SETTINGS) === true ? true : false,
'yubico' => isKeyExistingAndEqual('yubico_authentication', 1, $SETTINGS) === true ? true : false,
'duo' => isKeyExistingAndEqual('duo', 1, $SETTINGS) === true ? true : false,
],
'encode'
),
'key' => $session->get('key'),
]);
return false;
} elseif ($post_type === 'initiateSSOLogin') {
//--------
// Do initiateSSOLogin
//--------
//
// Création d'une instance du contrôleur
$OAuth2 = new OAuth2Controller($SETTINGS);
// Redirection vers Azure pour l'authentification
$OAuth2->redirect();
// Encrypt data to return
echo json_encode([
'key' => $session->get('key'),
]);
return false;
}
/**
* Complete authentication of user through Teampass
*
* @param string $sentData Credentials
* @param array $SETTINGS Teampass settings
*
* @return bool
*/
function identifyUser(string $sentData, array $SETTINGS): bool
{
$antiXss = new AntiXSS();
$session = SessionManager::getSession();
$request = SymfonyRequest::createFromGlobals();
$lang = new Language($session->get('user-language') ?? 'english');
$session = SessionManager::getSession();
// Prepare GET variables
$sessionAdmin = $session->get('user-admin');
$sessionPwdAttempts = $session->get('pwd_attempts');
$sessionUrl = $session->get('user-initial_url');
$server = [];
$server['PHP_AUTH_USER'] = $request->getUser();
$server['PHP_AUTH_PW'] = $request->getPassword();
// decrypt and retreive data in JSON format
if ($session->get('key') === null) {
$dataReceived = $sentData;
} else {
$dataReceived = prepareExchangedData(
$sentData,
'decode',
$session->get('key')
);
}
// Check if Duo auth is in progress and pass the pw and login back to the standard login process
if(
isKeyExistingAndEqual('duo', 1, $SETTINGS) === true
&& $dataReceived['user_2fa_selection'] === 'duo'
&& $session->get('user-duo_status') === 'IN_PROGRESS'
&& !empty($dataReceived['duo_state'])
){
$key = hash('sha256', $dataReceived['duo_state']);
$iv = substr(hash('sha256', $dataReceived['duo_state']), 0, 16);
$duo_data_dec = openssl_decrypt(base64_decode($session->get('user-duo_data')), 'AES-256-CBC', $key, 0, $iv);
// Clear the data from the Duo process to continue clean with the standard login process
$session->set('user-duo_data','');
if($duo_data_dec === false){
echo prepareExchangedData(
[
'error' => true,
'message' => $lang->get('duo_error_decrypt'),
],
'encode'
);
return false;
}
$duo_data = unserialize($duo_data_dec);
$dataReceived['pw'] = $duo_data['duo_pwd'];
$dataReceived['login'] = $duo_data['duo_login'];
}
if(isset($dataReceived['pw']) === false || isset($dataReceived['login']) === false) {
echo json_encode([
'data' => prepareExchangedData(
[
'error' => true,
'message' => $lang->get('ga_enter_credentials'),
],
'encode'
),
'key' => $session->get('key')
]);
return false;
}
// prepare variables
$userCredentials = identifyGetUserCredentials(
$SETTINGS,
(string) $server['PHP_AUTH_USER'],
(string) $server['PHP_AUTH_PW'],
(string) filter_var($dataReceived['pw'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
(string) filter_var($dataReceived['login'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)
);
$username = $userCredentials['username'];
$passwordClear = $userCredentials['passwordClear'];
// DO initial checks
$userInitialData = identifyDoInitialChecks(
$SETTINGS,
(int) $sessionPwdAttempts,
(string) $username,
(int) $sessionAdmin,
(string) $sessionUrl,
(string) filter_var($dataReceived['user_2fa_selection'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)
);
// if user doesn't exist in Teampass then return error
if ($userInitialData['error'] === true) {
echo prepareExchangedData(
$userInitialData['array'],
'encode'
);
return false;
}
$userInfo = $userInitialData['userInfo'] + $dataReceived;
$return = '';
// Check if LDAP is enabled and user is in AD
$userLdap = identifyDoLDAPChecks(
$SETTINGS,
$userInfo,
(string) $username,
(string) $passwordClear,
(int) $sessionAdmin,
(string) $sessionUrl,
(int) $sessionPwdAttempts
);
if ($userLdap['error'] === true) {
// deepcode ignore ServerLeak: File and path are secured directly inside the function decryptFile()
echo prepareExchangedData(
$userLdap['array'],
'encode'
);
return false;
}
if (isset($userLdap['user_info']) === true && (int) $userLdap['user_info']['has_been_created'] === 1) {
echo json_encode([
'data' => prepareExchangedData(
[
'error' => true,
'message' => '',
'extra' => 'ad_user_created',
],
'encode'
),
'key' => $session->get('key')
]);
return false;
}
// Should we create new oauth2 user?
$userOauth2 = createOauth2User(
(array) $SETTINGS,
(array) $userInfo,
(string) $username,
(string) $passwordClear,
(int) $userLdap['user_info']['has_been_created']
);
if ($userOauth2['error'] === true) {
$session->set('userOauth2Info', '');
// deepcode ignore ServerLeak: File and path are secured directly inside the function decryptFile()
echo prepareExchangedData(
[
'error' => true,
'message' => $lang->get($userOauth2['message']),
],
'encode'
);
return false;
}
// Check user and password
if ($userLdap['userPasswordVerified'] === false && $userOauth2['userPasswordVerified'] === false
&& checkCredentials($passwordClear, $userInfo) !== true
) {
echo prepareExchangedData(
[
'value' => '',
'user_admin' => isset($sessionAdmin) ? (int) $sessionAdmin : 0,
'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
'pwd_attempts' => (int) $sessionPwdAttempts,
'error' => true,
'message' => $lang->get('error_bad_credentials'),
],
'encode'
);
return false;
}
// Check if MFA is required
if ((isOneVarOfArrayEqualToValue(
[
(int) $SETTINGS['yubico_authentication'],
(int) $SETTINGS['google_authentication'],
(int) $SETTINGS['duo']
],
1
) === true)
&& (((int) $userInfo['admin'] !== 1 && (int) $userInfo['mfa_enabled'] === 1) || ((int) $SETTINGS['admin_2fa_required'] === 1 && (int) $userInfo['admin'] === 1))
&& $userInfo['mfa_auth_requested_roles'] === true
) {
// Check user against MFA method if selected
$userMfa = identifyDoMFAChecks(
$SETTINGS,
$userInfo,
$dataReceived,
$userInitialData,
(string) $username
);
if ($userMfa['error'] === true) {
echo prepareExchangedData(
[
'error' => true,
'message' => $userMfa['mfaData']['message'],
'mfaStatus' => $userMfa['mfaData']['mfaStatus'],
],
'encode'
);
return false;
} elseif ($userMfa['mfaQRCodeInfos'] === true) {
// Case where user has initiated Google Auth
// Return QR code
echo prepareExchangedData(
[
'value' => $userMfa['mfaData']['value'],
'user_admin' => isset($sessionAdmin) ? (int) $sessionAdmin : 0,
'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
'pwd_attempts' => (int) $sessionPwdAttempts,
'error' => false,
'message' => $userMfa['mfaData']['message'],
'mfaStatus' => $userMfa['mfaData']['mfaStatus'],
],
'encode'
);
return false;
} elseif ($userMfa['duo_url_ready'] === true) {
// Case where user has initiated Duo Auth
// Return the DUO redirect URL
echo prepareExchangedData(
[
'user_admin' => isset($sessionAdmin) ? (int) $sessionAdmin : 0,
'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
'pwd_attempts' => (int) $sessionPwdAttempts,
'error' => false,
'message' => $userMfa['mfaData']['message'],
'duo_url_ready' => $userMfa['mfaData']['duo_url_ready'],
'duo_redirect_url' => $userMfa['mfaData']['duo_redirect_url'],
'mfaStatus' => $userMfa['mfaData']['mfaStatus'],
],
'encode'
);
return false;
}
}
// Can connect if
// 1- no LDAP mode + user enabled + pw ok
// 2- LDAP mode + user enabled + ldap connection ok + user is not admin
// 3- LDAP mode + user enabled + pw ok + usre is admin
// This in order to allow admin by default to connect even if LDAP is activated
if (canUserGetLog(
$SETTINGS,
(int) $userInfo['disabled'],
$username,
$userLdap['ldapConnection']
) === true
) {
$session->set('pwd_attempts', 0);
// Check if any unsuccessfull login tries exist
$attemptsInfos = handleLoginAttempts(
$userInfo['id'],
$userInfo['login'],
$userInfo['last_connexion'],
$username,
$SETTINGS,
);
// Avoid unlimited session.
$max_time = isset($SETTINGS['maximum_session_expiration_time']) ? (int) $SETTINGS['maximum_session_expiration_time'] : 60;
$session_time = max(60, min($dataReceived['duree_session'], $max_time));
$lifetime = time() + ($session_time * 60);
// Save account in SESSION
$session->set('user-unsuccessfull_login_attempts_list', $attemptsInfos['attemptsList'] === 0 ? true : false);
$session->set('user-unsuccessfull_login_attempts_shown', $attemptsInfos['attemptsCount'] === 0 ? true : false);
$session->set('user-unsuccessfull_login_attempts_nb', DB::count());
$session->set('user-login', stripslashes($username));
$session->set('user-name', empty($userInfo['name']) === false ? stripslashes($userInfo['name']) : '');
$session->set('user-lastname', empty($userInfo['lastname']) === false ? stripslashes($userInfo['lastname']) : '');
$session->set('user-id', (int) $userInfo['id']);
$session->set('user-password', $passwordClear);
$session->set('user-admin', (int) $userInfo['admin']);
$session->set('user-manager', (int) $userInfo['gestionnaire']);
$session->set('user-can_manage_all_users', $userInfo['can_manage_all_users']);
$session->set('user-read_only', $userInfo['read_only']);
$session->set('user-last_pw_change', $userInfo['last_pw_change']);
$session->set('user-last_pw', $userInfo['last_pw']);
$session->set('user-force_relog', $userInfo['force-relog']);
$session->set('user-can_create_root_folder', $userInfo['can_create_root_folder']);
$session->set('user-email', $userInfo['email']);
//$session->set('user-ga', $userInfo['ga']);
$session->set('user-avatar', $userInfo['avatar']);
$session->set('user-avatar_thumb', $userInfo['avatar_thumb']);
$session->set('user-upgrade_needed', $userInfo['upgrade_needed']);
$session->set('user-is_ready_for_usage', $userInfo['is_ready_for_usage']);
$session->set('user-personal_folder_enabled', $userInfo['personal_folder']);
$session->set(
'user-tree_load_strategy',
(isset($userInfo['treeloadstrategy']) === false || empty($userInfo['treeloadstrategy']) === true) ? 'full' : $userInfo['treeloadstrategy']
);
$session->set(
'user-split_view_mode',
(isset($userInfo['split_view_mode']) === false || empty($userInfo['split_view_mode']) === true) ? 0 : $userInfo['split_view_mode']
);
$session->set('user-language', $userInfo['user_language']);
$session->set('user-timezone', $userInfo['usertimezone']);
$session->set('user-keys_recovery_time', $userInfo['keys_recovery_time']);
// manage session expiration
$session->set('user-session_duration', (int) $lifetime);
// User signature keys
$returnKeys = prepareUserEncryptionKeys($userInfo, $passwordClear);
$session->set('user-private_key', $returnKeys['private_key_clear']);
$session->set('user-public_key', $returnKeys['public_key']);
// Automatically detect LDAP password changes.
if ($userInfo['auth_type'] === 'ldap' && $returnKeys['private_key_clear'] === '') {
// Add special "recrypt-private-key" in database profile.
DB::update(
prefixTable('users'),
array(
'special' => 'recrypt-private-key',
),
'id = %i',
$userInfo['id']
);
// Store new value in userInfos.
$userInfo['special'] = 'recrypt-private-key';
}
// API key
$session->set(
'user-api_key',
empty($userInfo['api_key']) === false ? base64_decode(decryptUserObjectKey($userInfo['api_key'], $returnKeys['private_key_clear'])) : '',
);
$session->set('user-special', $userInfo['special']);
$session->set('user-auth_type', $userInfo['auth_type']);
// check feedback regarding user password validity
$return = checkUserPasswordValidity(
$userInfo,
(int) $session->get('user-num_days_before_exp'),
(int) $session->get('user-last_pw_change'),
$SETTINGS
);
$session->set('user-validite_pw', $return['validite_pw']);
$session->set('user-last_pw_change', $return['last_pw_change']);
$session->set('user-num_days_before_exp', $return['numDaysBeforePwExpiration']);
$session->set('user-force_relog', $return['user_force_relog']);
$session->set('user-last_connection', empty($userInfo['last_connexion']) === false ? (int) $userInfo['last_connexion'] : (int) time());
$session->set('user-latest_items', empty($userInfo['latest_items']) === false ? explode(';', $userInfo['latest_items']) : []);
$session->set('user-favorites', empty($userInfo['favourites']) === false ? explode(';', $userInfo['favourites']) : []);
$session->set('user-accessible_folders', empty($userInfo['groupes_visibles']) === false ? explode(';', $userInfo['groupes_visibles']) : []);
$session->set('user-no_access_folders', empty($userInfo['groupes_interdits']) === false ? explode(';', $userInfo['groupes_interdits']) : []);
// User's roles
if (strpos($userInfo['fonction_id'] !== NULL ? (string) $userInfo['fonction_id'] : '', ',') !== -1) {
// Convert , to ;
$userInfo['fonction_id'] = str_replace(',', ';', (string) $userInfo['fonction_id']);
DB::update(
prefixTable('users'),
[
'fonction_id' => $userInfo['fonction_id'],
],
'id = %i',
$session->get('user-id')
);
}
// Append with roles from AD groups
if (is_null($userInfo['roles_from_ad_groups']) === false) {
$userInfo['fonction_id'] = empty($userInfo['fonction_id']) === true ? $userInfo['roles_from_ad_groups'] : $userInfo['fonction_id']. ';' . $userInfo['roles_from_ad_groups'];
}
// store
$session->set('user-roles', $userInfo['fonction_id']);
$session->set('user-roles_array', array_unique(array_filter(explode(';', $userInfo['fonction_id']))));
// build array of roles
$session->set('user-pw_complexity', 0);
$session->set('system-array_roles', []);
if (count($session->get('user-roles_array')) > 0) {
$rolesList = DB::query(
'SELECT id, title, complexity
FROM ' . prefixTable('roles_title') . '
WHERE id IN %li',
$session->get('user-roles_array')
);
$excludeUser = isset($SETTINGS['exclude_user']) ? str_contains($session->get('user-login'), $SETTINGS['exclude_user']) : false;
$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'])));
if ($adjustPermissions) {
$userInfo['admin'] = $userInfo['gestionnaire'] = $userInfo['can_manage_all_users'] = $userInfo['read_only'] = 0;
}
foreach ($rolesList as $role) {
SessionManager::addRemoveFromSessionAssociativeArray(
'system-array_roles',
[
'id' => $role['id'],
'title' => $role['title'],
],
'add'
);
if ($adjustPermissions) {
if (isset($SETTINGS['admin_needle']) && str_contains($role['title'], $SETTINGS['admin_needle'])) {
$userInfo['gestionnaire'] = $userInfo['can_manage_all_users'] = $userInfo['read_only'] = 0;
$userInfo['admin'] = 1;
}
if (isset($SETTINGS['manager_needle']) && str_contains($role['title'], $SETTINGS['manager_needle'])) {
$userInfo['admin'] = $userInfo['can_manage_all_users'] = $userInfo['read_only'] = 0;
$userInfo['gestionnaire'] = 1;
}
if (isset($SETTINGS['tp_manager_needle']) && str_contains($role['title'], $SETTINGS['tp_manager_needle'])) {
$userInfo['admin'] = $userInfo['gestionnaire'] = $userInfo['read_only'] = 0;
$userInfo['can_manage_all_users'] = 1;
}
if (isset($SETTINGS['read_only_needle']) && str_contains($role['title'], $SETTINGS['read_only_needle'])) {
$userInfo['admin'] = $userInfo['gestionnaire'] = $userInfo['can_manage_all_users'] = 0;
$userInfo['read_only'] = 1;
}
}
// get highest complexity
if ($session->get('user-pw_complexity') < (int) $role['complexity']) {
$session->set('user-pw_complexity', (int) $role['complexity']);
}
}
if ($adjustPermissions) {
$session->set('user-admin', (int) $userInfo['admin']);
$session->set('user-manager', (int) $userInfo['gestionnaire']);
$session->set('user-can_manage_all_users',(int) $userInfo['can_manage_all_users']);
$session->set('user-read_only', (int) $userInfo['read_only']);
DB::update(
prefixTable('users'),
[
'admin' => $userInfo['admin'],
'gestionnaire' => $userInfo['gestionnaire'],
'can_manage_all_users' => $userInfo['can_manage_all_users'],
'read_only' => $userInfo['read_only'],
],
'id = %i',
$session->get('user-id')
);
}
}
// Set some settings
$SETTINGS['update_needed'] = '';
// Update table
DB::update(
prefixTable('users'),
array_merge(
[
'key_tempo' => $session->get('key'),
'last_connexion' => time(),
'timestamp' => time(),
'disabled' => 0,
'no_bad_attempts' => 0,
'session_end' => $session->get('user-session_duration'),
'user_ip' => $dataReceived['client'],
],
$returnKeys['update_keys_in_db']
),
'id=%i',
$userInfo['id']
);
// Get user's rights
if ($userLdap['user_initial_creation_through_external_ad'] === true || $userOauth2['retExternalAD']['has_been_created'] === 1) {
// is new LDAP user. Show only his personal folder
if ($SETTINGS['enable_pf_feature'] === '1') {
$session->set('user-personal_visible_folders', [$userInfo['id']]);
$session->set('user-personal_folders', [$userInfo['id']]);
} else {
$session->set('user-personal_visible_folders', []);
$session->set('user-personal_folders', []);
}
$session->set('user-all_non_personal_folders', []);
$session->set('user-roles_array', []);
$session->set('user-read_only_folders', []);
$session->set('user-list_folders_limited', []);
$session->set('system-list_folders_editable_by_role', []);
$session->set('system-list_restricted_folders_for_items', []);
$session->set('user-nb_folders', 1);
$session->set('user-nb_roles', 1);
} else {
identifyUserRights(
$userInfo['groupes_visibles'],
$session->get('user-no_access_folders'),
$userInfo['admin'],
$userInfo['fonction_id'],
$SETTINGS
);
}
// Get some more elements
$session->set('system-screen_height', $dataReceived['screenHeight']);
// Get last seen items
$session->set('user-latest_items_tab', []);
$session->set('user-nb_roles', 0);
foreach ($session->get('user-latest_items') as $item) {
if (! empty($item)) {
$dataLastItems = DB::queryFirstRow(
'SELECT id,label,id_tree
FROM ' . prefixTable('items') . '
WHERE id=%i',
$item
);
SessionManager::addRemoveFromSessionAssociativeArray(
'user-latest_items_tab',
[
'id' => $item,
'label' => $dataLastItems['label'],
'url' => 'index.php?page=items&group=' . $dataLastItems['id_tree'] . '&id=' . $item,
],
'add'
);
}
}
// Get cahce tree info
$cacheTreeData = DB::queryFirstRow(
'SELECT visible_folders
FROM ' . prefixTable('cache_tree') . '
WHERE user_id=%i',
(int) $session->get('user-id')
);
if (DB::count() > 0 && empty($cacheTreeData['visible_folders']) === true) {
$session->set('user-cache_tree', '');
// Prepare new task
DB::insert(
prefixTable('background_tasks'),
array(
'created_at' => time(),
'process_type' => 'user_build_cache_tree',
'arguments' => json_encode([
'user_id' => (int) $session->get('user-id'),
], JSON_HEX_QUOT | JSON_HEX_TAG),
'updated_at' => '',
'finished_at' => '',
'output' => '',
)
);
} else {
$session->set('user-cache_tree', $cacheTreeData['visible_folders']);
}
// send back the random key
$return = $dataReceived['randomstring'];
// Send email
if (
isKeyExistingAndEqual('enable_send_email_on_user_login', 1, $SETTINGS) === true
&& (int) $sessionAdmin !== 1
) {
// get all Admin users
$val = DB::queryfirstrow('SELECT email FROM ' . prefixTable('users') . " WHERE admin = %i and email != ''", 1);
if (DB::count() > 0) {
// Add email to table
prepareSendingEmail(
$lang->get('email_subject_on_user_login'),
str_replace(
[
'#tp_user#',
'#tp_date#',
'#tp_time#',
],
[
' ' . $session->get('user-login') . ' (IP: ' . getClientIpServer() . ')',
date($SETTINGS['date_format'], (int) $session->get('user-last_connection')),
date($SETTINGS['time_format'], (int) $session->get('user-last_connection')),
],
$lang->get('email_body_on_user_login')
),
$val['email'],
$lang->get('administrator')
);
}
}
// Ensure Complexity levels are translated
defineComplexity();
echo prepareExchangedData(
[
'value' => $return,
'user_id' => $session->get('user-id') !== null ? $session->get('user-id') : '',
'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
'initial_url' => $antiXss->xss_clean($sessionUrl),
'pwd_attempts' => 0,
'error' => false,
'message' => $session->has('user-upgrade_needed') && (int) $session->get('user-upgrade_needed') && (int) $session->get('user-upgrade_needed') === 1 ? 'ask_for_otc' : '',
'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
'private_key_conform' => $session->get('user-id') !== null
&& empty($session->get('user-private_key')) === false
&& $session->get('user-private_key') !== 'none' ? true : false,
'session_key' => $session->get('key'),
'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
'shown_warning_unsuccessful_login' => $session->get('user-unsuccessfull_login_attempts_shown'),
'nb_unsuccessful_logins' => $session->get('user-unsuccessfull_login_attempts_nb'),
'upgrade_needed' => isset($userInfo['upgrade_needed']) === true ? (int) $userInfo['upgrade_needed'] : 0,
'special' => isset($userInfo['special']) === true ? (int) $userInfo['special'] : 0,
'split_view_mode' => isset($userInfo['split_view_mode']) === true ? (int) $userInfo['split_view_mode'] : 0,
'validite_pw' => $session->get('user-validite_pw') !== null ? $session->get('user-validite_pw') : '',
'num_days_before_exp' => $session->get('user-num_days_before_exp') !== null ? (int) $session->get('user-num_days_before_exp') : '',
],
'encode'
);
return true;
} elseif ((int) $userInfo['disabled'] === 1) {
// User and password is okay but account is locked
echo prepareExchangedData(
[
'value' => $return,
'user_id' => $session->get('user-id') !== null ? (int) $session->get('user-id') : '',
'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
'pwd_attempts' => 0,
'error' => 'user_is_locked',
'message' => $lang->get('account_is_locked'),
'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
'private_key_conform' => $session->has('user-private_key') && null !== $session->get('user-private_key')
&& empty($session->get('user-private_key')) === false
&& $session->get('user-private_key') !== 'none' ? true : false,
'session_key' => $session->get('key'),
'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
'shown_warning_unsuccessful_login' => $session->get('user-unsuccessfull_login_attempts_shown'),
'nb_unsuccessful_logins' => $session->get('user-unsuccessfull_login_attempts_nb'),
],
'encode'
);
return false;
}
// DEFAULT CASE
// User exists in the DB but Password is false
// check if user is locked
if (isUserLocked(
(int) $userInfo['no_bad_attempts'],
$userInfo['id'],
$username,
$SETTINGS
) === true
) {
echo prepareExchangedData(
[
'value' => $return,
'user_id' => $session->get('user-id') !== null ? (int) $session->get('user-id') : '',
'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
'pwd_attempts' => 0,
'error' => 'user_is_locked',
'message' => $lang->get('account_is_locked'),
'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
'private_key_conform' => $session->get('user-id') !== null
&& empty($session->get('user-private_key')) === false
&& $session->get('user-private_key') !== 'none' ? true : false,
'session_key' => $session->get('key'),
'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
'shown_warning_unsuccessful_login' => $session->get('user-unsuccessfull_login_attempts_shown'),
'nb_unsuccessful_logins' => $session->get('user-unsuccessfull_login_attempts_nb'),
],
'encode'
);
return false;
}
echo prepareExchangedData(
[
'value' => $return,
'user_id' => $session->get('user-id') !== null ? (int) $session->get('user-id') : '',
'user_admin' => null !== $session->get('user-admin') ? $session->get('user-admin') : 0,
'initial_url' => isset($sessionUrl) === true ? $sessionUrl : '',
'pwd_attempts' => (int) $sessionPwdAttempts,
'error' => true,
'message' => $lang->get('error_not_allowed_to_authenticate'),
'first_connection' => $session->get('user-validite_pw') === 0 ? true : false,
'password_complexity' => TP_PW_COMPLEXITY[$session->get('user-pw_complexity')][1],
'password_change_expected' => $userInfo['special'] === 'password_change_expected' ? true : false,
'private_key_conform' => $session->get('user-id') !== null
&& empty($session->get('user-private_key')) === false
&& $session->get('user-private_key') !== 'none' ? true : false,
'session_key' => $session->get('key'),
'can_create_root_folder' => null !== $session->get('user-can_create_root_folder') ? (int) $session->get('user-can_create_root_folder') : '',
'shown_warning_unsuccessful_login' => $session->get('user-unsuccessfull_login_attempts_shown'),
'nb_unsuccessful_logins' => $session->get('user-unsuccessfull_login_attempts_nb'),
],
'encode'
);
return false;
}
/**
* Check if any unsuccessfull login tries exist
*
* @param int $userInfoId
* @param string $userInfoLogin
* @param string $userInfoLastConnection
* @param string $username
* @param array $SETTINGS
* @return array
*/
function handleLoginAttempts(
$userInfoId,
$userInfoLogin,
$userInfoLastConnection,
$username,
$SETTINGS
) : array
{
$rows = DB::query(
'SELECT date
FROM ' . prefixTable('log_system') . "
WHERE field_1 = %s
AND type = 'failed_auth'
AND label = 'password_is_not_correct'
AND date >= %s AND date < %s",
$userInfoLogin,
$userInfoLastConnection,
time()
);
$arrAttempts = [];
if (DB::count() > 0) {
foreach ($rows as $record) {
array_push(
$arrAttempts,
date($SETTINGS['date_format'] . ' ' . $SETTINGS['time_format'], (int) $record['date'])
);
}
}
// Log into DB the user's connection
if (isKeyExistingAndEqual('log_connections', 1, $SETTINGS) === true) {
logEvents($SETTINGS, 'user_connection', 'connection', (string) $userInfoId, stripslashes($username));
}
return [
'attemptsList' => $arrAttempts,
'attemptsCount' => count($rows),
];
}
/**
* Can you user get logged into main page
*
* @param array $SETTINGS
* @param int $userInfoDisabled
* @param string $username
* @param bool $ldapConnection
*
* @return boolean
*/
function canUserGetLog(
$SETTINGS,
$userInfoDisabled,