forked from glpi-project/glpi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuth.php
More file actions
1808 lines (1628 loc) · 63.3 KB
/
Copy pathAuth.php
File metadata and controls
1808 lines (1628 loc) · 63.3 KB
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
/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2026 Teclib' and contributors.
* @copyright 2003-2014 by the INDEPNET Development Team.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program 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, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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/>.
*
* ---------------------------------------------------------------------
*/
use Glpi\Application\View\TemplateRenderer;
use Glpi\DBAL\QueryFunction;
use Glpi\Error\ErrorHandler;
use Glpi\Event;
use Glpi\Plugin\Hooks;
use Glpi\Security\ReAuthManager;
use Glpi\Security\TOTPManager;
use Safe\Exceptions\LdapException;
use function Safe\ini_get;
use function Safe\json_decode;
use function Safe\json_encode;
use function Safe\ldap_bind;
use function Safe\parse_url;
use function Safe\preg_match;
use function Safe\session_name;
/**
* Identification class used to login
*/
class Auth extends CommonGLPI
{
/** @var array Array of errors */
private array $errors = [];
/** @var User User class variable */
public User $user;
/** @var int External authentication variable */
public int $extauth = 0;
/** @var array External authentication methods */
public array $authtypes;
/** @var bool Indicates if the user is authenticated or not */
public bool $auth_succeded = false;
/** @var bool Indicates if the user is already present in database */
public bool $user_present = false;
/** @var bool Indicates if the user password expired */
public bool $password_expired = false;
/** @var bool Indicates the login was valid by explicitly denied by a rule */
public bool $denied_by_rule = false;
/**
* Indicated if user was found in the directory.
*/
public bool $user_found = false;
/**
* The user's emails found during the validation part of the login workflow.
* @var string[]
*/
private array $user_emails = [];
/**
* The authentication method determined during the validation part of the login workflow.
*/
private int $auth_type = 0;
/**
* Indicates if an error occurs during connection to the user LDAP.
*/
public bool $user_ldap_error = false;
/** @var resource|bool LDAP connection descriptor */
public $ldap_connection;
/** @var string|false Store user LDAP dn */
public string|false $user_dn = false;
public const DB_GLPI = 1;
public const MAIL = 2;
public const LDAP = 3;
public const EXTERNAL = 4;
public const CAS = 5;
public const X509 = 6;
/**
* Authentication to the legacy API with a user_token or api_token.
* Not related to the High-Level REST API, which uses OAuth.
*/
public const API = 7;
public const COOKIE = 8;
public const NOT_YET_AUTHENTIFIED = 0;
public const USER_DOESNT_EXIST = 0;
public const USER_EXISTS_WITH_PWD = 1;
public const USER_EXISTS_WITHOUT_PWD = 2;
/**
* Constructor
*
* @return void
*/
public function __construct()
{
$this->user = new User();
}
public static function getMenuContent()
{
$menu = [];
if (Config::canUpdate()) {
$menu = [
'title' => __('Authentication'),
'page' => '/front/setup.auth.php',
'icon' => static::getIcon(),
'options' => [],
'links' => [],
];
$menu['options'][AuthLDAP::class] = [
'icon' => AuthLDAP::getIcon(),
'title' => AuthLDAP::getTypeName(Session::getPluralNumber()),
'page' => AuthLDAP::getSearchURL(false),
'links' => [
'search' => AuthLDAP::getSearchURL(false),
'add' => AuthLDAP::getFormURL(false),
],
];
$menu['options'][AuthMail::class] = [
'icon' => AuthMail::getIcon(),
'title' => AuthMail::getTypeName(Session::getPluralNumber()),
'page' => AuthMail::getSearchURL(false),
'links' => [
'search' => AuthMail::getSearchURL(false),
'add' => AuthMail::getFormURL(false),
],
];
$menu['options']['others'] = [
'icon' => 'ti ti-login',
'title' => __('Others'),
'page' => '/front/auth.others.php',
];
$menu['options']['settings'] = [
'icon' => 'ti ti-adjustments',
'title' => __('Setup'),
'page' => '/front/auth.settings.php',
];
}
if (count($menu)) {
return $menu;
}
return false;
}
/**
* Check user existence in DB
*
* Side effect : may also fill $this->user_dn
*
* @global DBmysql $DB
* @param array $options conditions : array('name'=>'glpi')
* or array('email' => 'test at test.com')
*
* @return int {@link Auth::USER_DOESNT_EXIST}, {@link Auth::USER_EXISTS_WITHOUT_PWD} or {@link Auth::USER_EXISTS_WITH_PWD}
*/
public function userExists($options = [])
{
global $DB;
$result = $DB->request([
'FROM' => 'glpi_users',
'LEFT JOIN' => [
'glpi_useremails' => [
'FKEY' => [
'glpi_users' => 'id',
'glpi_useremails' => 'users_id',
],
],
],
'WHERE' => $options,
]);
// Check if there is a row
if (count($result) === 0) {
$this->addToError(__('Incorrect username or password'));
return self::USER_DOESNT_EXIST;
} else {
// Get the first result...
$row = $result->current();
// Check if we have a password...
if (empty($row['password'])) {
// If the user has an LDAP DN, then store it in the Auth object
if ($row['user_dn']) {
$this->user_dn = $row['user_dn'];
}
return self::USER_EXISTS_WITHOUT_PWD;
}
return self::USER_EXISTS_WITH_PWD;
}
}
/**
* User can log in
*
* All conditions to meet :
* - User is not deleted
* - active
* - current time between restricted dates
*/
public function canUserLogin(): bool
{
// in some contexts, we can have "NULL" as string instead of null value
if ($this->user->fields['begin_date'] === 'NULL') {
$this->user->fields['begin_date'] = null;
}
if ($this->user->fields['end_date'] === 'NULL') {
$this->user->fields['begin_date'] = null;
}
return
$this->user->fields['is_deleted'] === 0
&& (
$this->user->fields['is_active'] === 1
&& (
($this->user->fields['begin_date'] < $_SESSION["glpi_currenttime"])
|| is_null($this->user->fields['begin_date'])
)
&& (
($this->user->fields['end_date'] > $_SESSION["glpi_currenttime"])
|| is_null($this->user->fields['end_date'])
)
);
}
/**
* Try a IMAP/POP connection
*
* @param string $host IMAP/POP host to connect
* @param string $login Login to try
* @param string $pass Password to try
*
* @return bool connection success
*/
public function connection_imap($host, $login, $pass)
{
// we prevent some delay...
if (empty($host)) {
return false;
}
// No retry (avoid lock account when password is not correct)
try {
$config = Toolbox::parseMailServerConnectString($host, false, false);
$ssl = false;
if ($config['ssl']) {
$ssl = 'SSL';
}
if ($config['tls']) {
$ssl = 'TLS';
}
$protocol = Toolbox::getMailServerProtocolInstance($config['type'], false);
if ($protocol === null) {
throw new RuntimeException(sprintf(__('Unsupported mail server type:%s.'), $config['type']));
}
if ($config['validate-cert'] === false) {
$protocol->setNoValidateCert(true);
}
$protocol->connect(
$config['address'],
$config['port'],
$ssl
);
return $protocol->login($login, $pass);
} catch (Throwable $e) {
$this->addToError($e->getMessage());
return false;
}
}
/**
* Find a user in LDAP
* Based on GRR auth system
*
* @param array $ldap_method ldap_method array to use
* @param string $login User Login
* @param string $password User Password
* @param bool $error Boolean flag that will be set to `true` if a LDAP error occurs during connection
*
* @return false|array
*/
public function connection_ldap($ldap_method, $login, $password, bool &$error = false)
{
$error = false;
// we prevent some delay...
if (empty($ldap_method['host'])) {
$error = true;
return false;
}
$this->ldap_connection = AuthLDAP::tryToConnectToServer($ldap_method, $login, $password);
$this->user_found = false;
if ($this->ldap_connection) {
$params = [
'method' => AuthLDAP::IDENTIFIER_LOGIN,
'fields' => [
AuthLDAP::IDENTIFIER_LOGIN => $ldap_method['login_field'],
],
];
if (!empty($ldap_method['sync_field'])) {
$params['fields']['sync_field'] = $ldap_method['sync_field'];
}
try {
$info = AuthLDAP::searchUserDn($this->ldap_connection, [
'basedn' => $ldap_method['basedn'],
'login_field' => $ldap_method['login_field'],
'search_parameters' => $params,
'user_params' => [
'method' => AuthLDAP::IDENTIFIER_LOGIN,
'value' => $login,
],
'condition' => $ldap_method['condition'],
'user_dn' => $this->user_dn,
]);
} catch (Throwable $e) {
ErrorHandler::logCaughtException($e);
$info = false;
}
$ldap_errno = ldap_errno($this->ldap_connection);
if ($info === false) {
if ($ldap_errno > 0 && $ldap_errno !== 32) {
$this->addToError(__('Unable to connect to the LDAP directory'));
$error = true;
} else {
// 32 = LDAP_NO_SUCH_OBJECT => This should not be considered as a connection error, as it just means that user was not found.
$this->addToError(__('Incorrect username or password'));
}
return false;
}
$dn = $info['dn'];
$this->user_found = $dn !== '';
if ($this->user_found) {
try {
@ldap_bind($this->ldap_connection, $dn, $password);
// Hook to implement to restrict access by checking the ldap directory
if (Plugin::doHookFunction(Hooks::RESTRICT_LDAP_AUTH, $info)) {
return $info;
}
$this->addToError(__('User not authorized to connect in GLPI'));
// Use is present by has no right to connect because of a plugin
return false;
} catch (LdapException $e) {
//empty catch
}
}
// Incorrect login
$this->addToError(__('Incorrect username or password'));
//Use is not present anymore in the directory!
return false;
} else {
// Directory is not available
$this->addToError(__('Unable to connect to the LDAP directory'));
$error = true;
return false;
}
}
/**
* Check is a password match the stored hash
*
* @since 0.85
*
* @param string $pass Password (pain-text)
* @param string $hash Hash
*
* @return bool
*/
public static function checkPassword($pass, $hash)
{
$tmp = password_get_info($hash);
if (isset($tmp['algo']) && $tmp['algo']) {
$ok = password_verify($pass, $hash);
} elseif (strlen($hash) === 32) {
$ok = md5($pass) === $hash;
} elseif (strlen($hash) === 40) {
$ok = sha1($pass) === $hash;
} else {
$salt = substr($hash, 0, 8);
$ok = ($salt . sha1($salt . $pass) === $hash);
}
return $ok;
}
/**
* Is the hash stored need to be regenerated
*
* @since 0.85
*
* @param string $hash Hash
*
* @return bool
*/
public static function needRehash($hash)
{
return password_needs_rehash($hash, PASSWORD_DEFAULT);
}
/**
* Compute the hash for a password
*
* @since 0.85
*
* @param string $pass Password
*
* @return string
*/
public static function getPasswordHash($pass)
{
return password_hash($pass, PASSWORD_DEFAULT);
}
/**
* Find a user in the GLPI DB
*
* try to connect to DB
* update the instance variable user with the user who has the name $name
* and the password is $password in the DB.
* If not found or can't connect to DB updates the instance variable err
* with an eventual error message
*
* @global DBmysql $DB
* @param string $name User Login
* @param string $password User Password
*
* @return bool user in GLPI DB with the right password
*/
public function connection_db($name, $password)
{
global $CFG_GLPI, $DB;
$pass_expiration_delay = (int) $CFG_GLPI['password_expiration_delay'];
$lock_delay = (int) $CFG_GLPI['password_expiration_lock_delay'];
// SQL query
$result = $DB->request(
[
'SELECT' => [
'id',
'password',
QueryFunction::dateAdd(
date: 'password_last_update',
interval: $pass_expiration_delay,
interval_unit: 'DAY',
alias: 'password_expiration_date'
),
QueryFunction::dateAdd(
date: 'password_last_update',
interval: $pass_expiration_delay + $lock_delay,
interval_unit: 'DAY',
alias: 'lock_date'
),
],
'FROM' => User::getTable(),
'WHERE' => [
'name' => $name,
'authtype' => self::DB_GLPI,
'auths_id' => 0,
],
]
);
// Have we a result ?
if (count($result) === 1) {
$row = $result->current();
$password_db = $row['password'];
if (self::checkPassword($password, $password_db)) {
// Disable account if password expired
if (
-1 !== $pass_expiration_delay && -1 !== $lock_delay
&& $row['lock_date'] < $_SESSION['glpi_currenttime']
) {
$user = new User();
$user->update(
[
'id' => $row['id'],
'is_active' => 0,
]
);
}
if (
-1 !== $pass_expiration_delay
&& $row['password_expiration_date'] < $_SESSION['glpi_currenttime']
) {
$this->password_expired = true;
}
// Update password if needed
if (self::needRehash($password_db)) {
$DB->update(
User::getTable(),
['password' => password_hash($password, PASSWORD_DEFAULT)],
['id' => $row['id']]
);
}
$this->user->getFromDBByCrit(['id' => $row['id']]);
$this->extauth = 0;
$this->user_present = true;
$this->user->fields["authtype"] = self::DB_GLPI;
$this->user->fields["password"] = $password;
// apply rule rights on local user
$rules = new RuleRightCollection();
$groups = Group_User::getUserGroups($row['id']);
$groups_id = array_column($groups, 'id');
$result = $rules->processAllRules(
$groups_id,
$this->user->fields,
[
'type' => Auth::DB_GLPI,
'login' => $this->user->fields['name'],
'email' => UserEmail::getDefaultForUser($row['id']),
]
);
$this->user->fields = $result;
$this->user->willProcessRuleRight();
return true;
}
}
$this->addToError(__('Incorrect username or password'));
return false;
}
/**
* Try to get login of external auth method
*
* @param int $authtype external auth type (default 0)
*
* @return bool user login success
*/
public function getAlternateAuthSystemsUserLogin($authtype = 0)
{
global $CFG_GLPI;
switch ($authtype) {
case self::CAS:
$url_base = parse_url($CFG_GLPI["url_base"]);
$service_base_url = $url_base["scheme"] . "://" . $url_base["host"] . (isset($url_base["port"]) ? ":" . $url_base["port"] : "");
phpCAS::client(
constant($CFG_GLPI["cas_version"]),
$CFG_GLPI["cas_host"],
(int) $CFG_GLPI["cas_port"],
$CFG_GLPI["cas_uri"],
$service_base_url,
false
);
// no SSL validation for the CAS server
phpCAS::setNoCasServerValidation();
// force CAS authentication
phpCAS::forceAuthentication();
$this->user->fields['name'] = phpCAS::getUser();
// extract e-mail information
if (phpCAS::hasAttribute("mail")) {
$this->user->fields['_useremails'] = [phpCAS::getAttribute("mail")];
}
return true;
case self::EXTERNAL:
$ssovariable = Dropdown::getDropdownName(
'glpi_ssovariables',
$CFG_GLPI["ssovariables_id"]
);
$login_string = '';
// MoYo : checking REQUEST create a security hole for me !
if (isset($_SERVER[$ssovariable])) {
$login_string = $_SERVER[$ssovariable];
}
$login = $login_string;
$pos = strpos($login_string, "\\");
if ($pos !== false) {
$login = substr($login_string, $pos + 1);
}
if ($CFG_GLPI['existing_auth_server_field_clean_domain']) {
$pos = strpos($login, "@");
if ($pos !== false) {
$login = substr($login, 0, $pos);
}
}
if (self::isValidLogin($login)) {
$this->user->fields['name'] = $login;
// Get data from SSO if defined
$ret = $this->user->getFromSSO();
if (!$ret) {
return false;
}
$_SESSION['glpi_remote_user'] = $login_string; // store raw remote user
return true;
}
break;
case self::X509:
// From eGroupWare http://www.egroupware.org
// an X.509 subject looks like:
// CN=john.doe/OU=Department/O=Company/C=xx/Email=john@comapy.tld/L=City/
$sslattribs = explode('/', $_SERVER['SSL_CLIENT_S_DN']);
$sslattributes = [];
while ($sslattrib = next($sslattribs)) {
[$key, $val] = explode('=', $sslattrib);
$sslattributes[$key] = $val;
}
if (
isset($sslattributes[$CFG_GLPI["x509_email_field"]])
&& NotificationMailing::isUserAddressValid($sslattributes[$CFG_GLPI["x509_email_field"]])
&& self::isValidLogin($sslattributes[$CFG_GLPI["x509_email_field"]])
) {
$restrict = false;
$CFG_GLPI["x509_ou_restrict"] = trim($CFG_GLPI["x509_ou_restrict"]);
if (!empty($CFG_GLPI["x509_ou_restrict"])) {
$split = explode('$', $CFG_GLPI["x509_ou_restrict"]);
if (!in_array($sslattributes['OU'], $split, true)) {
$restrict = true;
}
}
$CFG_GLPI["x509_o_restrict"] = trim($CFG_GLPI["x509_o_restrict"]);
if (!empty($CFG_GLPI["x509_o_restrict"])) {
$split = explode('$', $CFG_GLPI["x509_o_restrict"]);
if (!in_array($sslattributes['O'], $split, true)) {
$restrict = true;
}
}
$CFG_GLPI["x509_cn_restrict"] = trim($CFG_GLPI["x509_cn_restrict"]);
if (!empty($CFG_GLPI["x509_cn_restrict"])) {
$split = explode('$', $CFG_GLPI["x509_cn_restrict"]);
if (!in_array($sslattributes['CN'], $split, true)) {
$restrict = true;
}
}
if (!$restrict) {
$this->user->fields['name'] = $sslattributes[$CFG_GLPI["x509_email_field"]];
// Can do other things if need : only add it here
$this->user->fields['email'] = $this->user->fields['name'];
return true;
}
}
break;
case self::API:
if ($CFG_GLPI['enable_api_login_external_token']) {
$user = new User();
if ($user->getFromDBbyToken($_REQUEST['user_token'], 'api_token')) {
$this->user->fields['name'] = $user->fields['name'];
return true;
}
} else {
$this->addToError(__("Login with external token disabled"));
}
break;
case self::COOKIE:
$cookie_name = session_name() . '_rememberme';
if ($CFG_GLPI["login_remember_time"]) {
$data = null;
if (array_key_exists($cookie_name, $_COOKIE)) {
$data = json_decode($_COOKIE[$cookie_name], true);
}
if (is_array($data) && count($data) === 2) {
[$cookie_id, $cookie_token] = $data;
$user = new User();
$user->getFromDB($cookie_id);
$hash = $user->getAuthToken('cookie_token');
if (self::checkPassword($cookie_token, $hash)) {
$this->user->fields['name'] = $user->fields['name'];
// Use current time as session time may not be initialized yet or may be from previous session
$user->update(['id' => $user->getID(), 'last_login' => date("Y-m-d H:i:s")]);
return true;
} else {
$this->addToError(__("Invalid cookie data"));
}
}
} else {
$this->addToError(__("Auto login disabled"));
}
// Remove cookie to allow new login
self::setRememberMeCookie('');
break;
}
return false;
}
/**
* Get errors
*
* @since 9.4
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* Get the current user object
*
* @return object current user
*/
public function getUser()
{
return $this->user;
}
/**
* Get all the authentication methods parameters
* and return it as an array
*
* @return void
*/
public function getAuthMethods()
{
//Return all the authentication methods in an array
$this->authtypes = [
'ldap' => getAllDataFromTable('glpi_authldaps'),
'mail' => getAllDataFromTable('glpi_authmails'),
];
}
/**
* Add a message to the global identification error message
*
* @param string $message the message to add
*
* @return void
*/
public function addToError($message)
{
if (!in_array($message, $this->errors, true)) {
$this->errors[] = $message;
}
}
/**
* Checks if a user can log in with the given username, password, and auth type without actually logging them in.
*
* This process will create the user in GLPI if they are provided by an external source, and runs the LDAP deleted user workflow if needed.
* This method modifies the Auth object's properties.
* More information about the login validation can be retreived from those properties.
* If testing more than one set of credentials, it is best to use a new Auth object for each set of credentials.
* The {@link user} property may have some updated fields set here, but they will not be saved to the database
* (unless this function was called by {@link login()} in which case the login function will trigger the update).
* @param string $login_name Login
* @param string $login_password Password
* @param bool $noauto
* @param string $login_auth Type of auth
* @return bool True if the user could log in, false otherwise
*/
public function validateLogin(string $login_name, string $login_password, bool $noauto = false, string $login_auth = ''): bool
{
$this->getAuthMethods();
$this->user_present = true;
$this->auth_succeded = false;
//In case the user was deleted in the LDAP directory
$user_deleted_ldap = false;
// Trim login_name : avoid LDAP search errors
$login_name = trim($login_name);
// manage the $login_auth (force the auth source of the user account)
$this->user->fields["auths_id"] = 0;
if ($login_auth === 'local') {
$this->auth_type = self::DB_GLPI;
$this->user->fields["authtype"] = self::DB_GLPI;
} elseif (preg_match('/^(?<type>ldap|mail|external)-(?<id>\d+)$/', $login_auth, $auth_matches)) {
$this->user->fields["auths_id"] = (int) $auth_matches['id'];
if ($auth_matches['type'] === 'ldap') {
$this->auth_type = self::LDAP;
} elseif ($auth_matches['type'] === 'mail') {
$this->auth_type = self::MAIL;
} elseif ($auth_matches['type'] === 'external') {
$this->auth_type = self::EXTERNAL;
}
$this->user->fields['authtype'] = $this->auth_type;
}
if (!$noauto && ($this->auth_type = self::checkAlternateAuthSystems())) {
if (
$this->getAlternateAuthSystemsUserLogin($this->auth_type)
&& !empty($this->user->fields['name'])
) {
// Used for log when login process failed
$login_name = $this->user->fields['name'];
$this->auth_succeded = true;
$this->user_present = $this->user->getFromDBbyName($login_name);
$this->extauth = 1;
$user_dn = false;
if (array_key_exists('_useremails', $this->user->fields)) {
$this->user_emails = $this->user->fields['_useremails'];
}
$ldapservers = [];
$ldapservers_status = false;
//if LDAP enabled too, get user's infos from LDAP
if ((!isset($this->user->fields['authtype']) || $this->user->fields['authtype'] === self::LDAP) && Toolbox::canUseLdap()) {
//User has already authenticated, at least once: its ldap server is filled
if ($this->user->fields["auths_id"] > 0) {
$authldap = new AuthLDAP();
//If ldap server is enabled
if (
$authldap->getFromDB($this->user->fields["auths_id"])
&& $authldap->fields['is_active']
) {
$ldapservers[] = $authldap->fields;
}
} else { // User has never been authenticated: try all active ldap server to find the right one
foreach (getAllDataFromTable('glpi_authldaps', ['is_active' => 1]) as $ldap_config) {
$ldapservers[] = $ldap_config;
}
}
foreach ($ldapservers as $ldap_method) {
$ds = AuthLDAP::connectToServer(
$ldap_method["host"],
$ldap_method["port"],
$ldap_method["rootdn"],
(new GLPIKey())->decrypt($ldap_method["rootdn_passwd"]),
$ldap_method["use_tls"],
$ldap_method["deref_option"],
$ldap_method["tls_certfile"],
$ldap_method["tls_keyfile"],
$ldap_method["use_bind"],
$ldap_method["timeout"],
$ldap_method["tls_version"]
);
if ($ds) {
$ldapservers_status = true;
$params = [
'method' => AuthLDAP::IDENTIFIER_LOGIN,
'fields' => [
AuthLDAP::IDENTIFIER_LOGIN => $ldap_method["login_field"],
],
];
try {
$user_dn = AuthLDAP::searchUserDn($ds, [
'basedn' => $ldap_method["basedn"],
'login_field' => $ldap_method['login_field'],
'search_parameters' => $params,
'condition' => $ldap_method["condition"],
'user_params' => [
'method' => AuthLDAP::IDENTIFIER_LOGIN,
'value' => $login_name,
],
]);
} catch (RuntimeException $e) {
ErrorHandler::logCaughtException($e);
$user_dn = false;
}
if ($user_dn) {
$this->user_found = true;
$this->user->fields['auths_id'] = $ldap_method['id'];
$this->user->getFromLDAP(
$ds,
$ldap_method,
$user_dn['dn'],
$login_name,
!$this->user_present
);
break;
}
}
}
}
if (
(count($ldapservers) === 0)
&& ($this->auth_type === self::EXTERNAL)
) {
// Case of using external auth and no LDAP servers, so get data from external auth
$this->user->getFromSSO();
$this->user_present = !$this->user->isNewItem();
} else {
if ($this->user->fields['authtype'] === self::LDAP) {
if (!$ldapservers_status) {
$this->auth_succeded = false;
$this->addToError(_n(
'Connection to LDAP directory failed',
'Connection to LDAP directories failed',
count($ldapservers)
));
} elseif (!$user_dn && $this->user_present) {
//If user is set as present in GLPI but no LDAP DN found : it means that the user
//is not present in an ldap directory anymore
$user_deleted_ldap = true;
$this->addToError(_n(
'User not found in LDAP directory',
'User not found in LDAP directories',
count($ldapservers)
));
}
}
}
// Reset to secure it
$this->user->fields['name'] = $login_name;
// Use current time as session time may not be initialized yet or may be from previous session
$this->user->fields["last_login"] = date("Y-m-d H:i:s");
} else {
$this->addToError(__('Empty login or password'));
}
}
if (!$this->auth_succeded) {
if (
empty($login_name) || str_contains($login_name, "\0")
|| empty($login_password) || str_contains($login_password, "\0")
) {
$this->addToError(__('Empty login or password'));
} else {
// Try connect local user if not yet authenticated
if (
empty($login_auth)
|| $this->user->fields["authtype"] === static::DB_GLPI
) {
$this->auth_succeded = $this->connection_db(
$login_name,
$login_password
);
}
// Try to connect LDAP user if not yet authenticated
if (!$this->auth_succeded) {
if (
empty($login_auth)
|| $this->user->fields["authtype"] === static::CAS
|| $this->user->fields["authtype"] === static::EXTERNAL
|| $this->user->fields["authtype"] === static::LDAP
) {
if (Toolbox::canUseLdap()) {
AuthLDAP::tryLdapAuth(
$this,
$login_name,
$login_password,
$this->user->fields["auths_id"]
);
// PHPstan thinks $this->auth_succeded is always true because it is checking in a previous
// condition.
// It seems dangerous to remove it because $this is passed to AuthLDAP::tryLdapAuth right
// before this code, which mean the auth_succeded property could be modified.
// Keep this phpstan-ignore instruction until this code is improved to avoid risky behavior like this.
if ($this->user_ldap_error === false && !$this->auth_succeded && !$this->user_found) { // @phpstan-ignore booleanNot.alwaysTrue
$search_params = [