/
class.auth.php
1404 lines (1131 loc) · 44.6 KB
/
class.auth.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
interface AuthenticatedUser {
/* PHP 5.3 < 5.3.8 will crash with some abstract inheritance issue
* ------------------------------------------------------------
// Get basic information
function getId();
function getUsername();
function getUserType();
//Backend used to authenticate the user
function getAuthBackend();
//Authentication key
function setAuthKey($key);
function getAuthKey();
// logOut the user
function logOut();
// Signal method to allow performing extra things when a user is logged
// into the sysem
function onLogin($bk);
*/
}
abstract class BaseAuthenticatedUser
implements AuthenticatedUser {
//Authorization key returned by the backend used to authorize the user
private $authkey;
// Get basic information
abstract function getId();
abstract function getUsername();
abstract function getUserType();
//Backend used to authenticate the user
abstract function getAuthBackend();
//Authentication key
function setAuthKey($key) {
$this->authkey = $key;
}
function getAuthKey() {
return $this->authkey;
}
// logOut the user
function logOut() {
if ($bk = $this->getAuthBackend())
return $bk->signOut($this);
return false;
}
// Signal method to allow performing extra things when a user is logged
// into the sysem
function onLogin($bk) {}
}
require_once(INCLUDE_DIR.'class.ostsession.php');
require_once(INCLUDE_DIR.'class.usersession.php');
interface AuthDirectorySearch {
/**
* Indicates if the backend can be used to search for user information.
* Lookup is performed to find user information based on a unique
* identifier.
*/
function lookup($id);
/**
* Indicates if the backend supports searching for usernames. This is
* distinct from information lookup in that lookup is intended to lookup
* information based on a unique identifier
*/
function search($query);
}
/**
* Class: ClientCreateRequest
*
* Simple container to represent a remote authentication success for a
* client which should be imported into the local database. The class will
* provide access to the backend that authenticated the user, the username
* that the user entered when logging in, and any other information about
* the user that the backend was able to lookup. Generally, this extra
* information would be the same information retrieved from calling the
* AuthDirectorySearch::lookup() method.
*/
class ClientCreateRequest {
var $backend;
var $username;
var $info;
function __construct($backend, $username, $info=array()) {
$this->backend = $backend;
$this->username = $username;
$this->info = $info;
}
function getBackend() {
return $this->backend;
}
function setBackend($what) {
$this->backend = $what;
}
function getUsername() {
return $this->username;
}
function getInfo() {
return $this->info;
}
function attemptAutoRegister() {
global $cfg;
if (!$cfg)
return false;
// Attempt to automatically register
$this_form = UserForm::getUserForm()->getForm($this->getInfo());
$bk = $this->getBackend();
$defaults = array(
'timezone' => $cfg->getDefaultTimezone(),
'username' => $this->getUsername(),
);
if ($bk->supportsInteractiveAuthentication())
// User can only be authenticated against this backend
$defaults['backend'] = $bk::$id;
if ($this_form->isValid(function($f) { return !$f->isVisibleToUsers(); })
&& ($U = User::fromVars($this_form->getClean()))
&& ($acct = ClientAccount::createForUser($U, $defaults))
// Confirm and save the account
&& $acct->confirm()
// Login, since `tickets.php` will not attempt SSO
&& ($cl = new ClientSession(new EndUser($U)))
&& ($bk->login($cl, $bk)))
return $cl;
}
}
/**
* Authentication backend
*
* Authentication provides the basis of abstracting the link between the
* login page with a username and password and the staff member,
* administrator, or client using the system.
*
* The system works by allowing the AUTH_BACKENDS setting from
* ost-config.php to determine the list of authentication backends or
* providers and also specify the order they should be evaluated in.
*
* The authentication backend should define a authenticate() method which
* receives a username and optional password. If the authentication
* succeeds, an instance deriving from <User> should be returned.
*/
abstract class AuthenticationBackend {
static protected $registry = array();
static $name;
static $id;
/* static */
static function register($class) {
if (is_string($class) && class_exists($class))
$class = new $class();
if (!is_object($class)
|| !($class instanceof AuthenticationBackend))
return false;
return static::_register($class);
}
static function _register($class) {
// XXX: Raise error if $class::id is already in the registry
static::$registry[$class::$id] = $class;
}
static function allRegistered() {
return static::$registry;
}
static function getBackend($id) {
if ($id
&& ($backends = static::allRegistered())
&& isset($backends[$id]))
return $backends[$id];
}
static function getSearchDirectoryBackend($id) {
if ($id
&& ($backends = static::getSearchDirectories())
&& isset($backends[$id]))
return $backends[$id];
}
/*
* Allow the backend to do login audit depending on the result
* This is mainly used to track failed login attempts
*/
static function authAudit($result, $credentials=null) {
if (!$result) return;
foreach (static::allRegistered() as $bk)
$bk->audit($result, $credentials);
}
static function process($username, $password=null, &$errors=array()) {
if (!$username)
return false;
$backends = static::getAllowedBackends($username);
foreach (static::allRegistered() as $bk) {
if ($backends //Allowed backends
&& $bk->supportsInteractiveAuthentication()
&& !in_array($bk::$id, $backends))
// User cannot be authenticated against this backend
continue;
// All backends are queried here, even if they don't support
// authentication so that extensions like lockouts and audits
// can be supported.
try {
$result = $bk->authenticate($username, $password);
if ($result instanceof AuthenticatedUser
&& ($bk->login($result, $bk)))
return $result;
elseif ($result instanceof ClientCreateRequest
&& $bk instanceof UserAuthenticationBackend)
return $result;
elseif ($result instanceof AccessDenied) {
break;
}
}
catch (AccessDenied $e) {
$result = $e;
break;
}
}
if (!$result)
$result = new AccessDenied(__('Access denied'));
if ($result && $result instanceof AccessDenied)
$errors['err'] = $result->reason;
$info = array('username' => $username, 'password' => $password);
Signal::send('auth.login.failed', null, $info);
self::authAudit($result, $info);
}
/*
* Attempt to process non-interactive sign-on e.g HTTP-Passthrough
*
* $forcedAuth - indicate if authentication is required.
*
*/
function processSignOn(&$errors, $forcedAuth=true) {
foreach (static::allRegistered() as $bk) {
// All backends are queried here, even if they don't support
// authentication so that extensions like lockouts and audits
// can be supported.
try {
$result = $bk->signOn();
if ($result instanceof AuthenticatedUser) {
//Perform further Object specific checks and the actual login
if (!$bk->login($result, $bk))
continue;
return $result;
}
elseif ($result instanceof ClientCreateRequest
&& $bk instanceof UserAuthenticationBackend)
return $result;
elseif ($result instanceof AccessDenied) {
break;
}
}
catch (AccessDenied $e) {
$result = $e;
break;
}
}
if (!$result && $forcedAuth)
$result = new AccessDenied(__('Unknown user'));
if ($result && $result instanceof AccessDenied)
$errors['err'] = $result->reason;
self::authAudit($result);
}
static function getSearchDirectories() {
$backends = array();
foreach (StaffAuthenticationBackend::allRegistered() as $bk)
if ($bk instanceof AuthDirectorySearch)
$backends[$bk::$id] = $bk;
foreach (UserAuthenticationBackend::allRegistered() as $bk)
if ($bk instanceof AuthDirectorySearch)
$backends[$bk::$id] = $bk;
return array_unique($backends);
}
static function searchUsers($query) {
$users = array();
foreach (static::getSearchDirectories() as $bk)
$users = array_merge($users, $bk->search($query));
return $users;
}
/**
* Fetches the friendly name of the backend
*/
function getName() {
return static::$name;
}
/**
* Indicates if the backed supports authentication. Useful if the
* backend is used for logging or lockout only
*/
function supportsInteractiveAuthentication() {
return true;
}
/**
* Indicates if the backend supports changing a user's password. This
* would be done in two fashions. Either the currently-logged in user
* want to change its own password or a user requests to have their
* password reset. This requires an administrative privilege which this
* backend might not possess, so it's defined in supportsPasswordReset()
*/
function supportsPasswordChange() {
return false;
}
/**
* Request the backend to update the password for a user. This method is
* the main entry for password updates so that password policies can be
* applied to the new password before passing the new password to the
* backend for updating.
*
* Throws:
* BadPassword — if password does not meet policy requirement
* PasswordUpdateFailed — if backend failed to update the password
*/
function setPassword($user, $password, $current=false) {
PasswordPolicy::checkPassword($password, $current);
$rv = $this->syncPassword($user, $password);
if ($rv) {
$info = array('password' => $password, 'current' => $current);
Signal::send('auth.pwchange', $user, $info);
}
return $rv;
}
/**
* Request the backend to update the user's password with the password
* given. This method should only be used if the backend advertises
* supported password updates with the supportsPasswordChange() method.
*
* Returns:
* true if the password was successfully updated and false otherwise.
*/
protected function syncPassword($user, $password) {
return false;
}
function supportsPasswordReset() {
return false;
}
function signOn() {
return null;
}
protected function validate($auth) {
return null;
}
protected function audit($result, $credentials) {
return null;
}
abstract function authenticate($username, $password);
abstract function login($user, $bk);
abstract static function getUser(); //Validates authenticated users.
abstract function getAllowedBackends($userid);
abstract protected function getAuthKey($user);
abstract static function signOut($user);
}
/**
* ExternalAuthenticationBackend
*
* External authentication backends are backends such as Google+ which
* require a redirect to a remote site and a redirect back to osTicket in
* order for a user to be authenticated. For such backends, neither the
* username and password fields nor single sign on alone can be used to
* authenticate the user.
*/
interface ExternalAuthentication {
/**
* Requests the backend to render an external link box. When the user
* clicks this box, the backend will be prompted to redirect the user to
* the remote site for authentication there.
*/
function renderExternalLink();
/**
* Function: triggerAuth
*
* Called when a user clicks the button rendered in the
* ::renderExternalLink() function. This method should initiate the
* remote authentication mechanism.
*/
function triggerAuth();
}
abstract class StaffAuthenticationBackend extends AuthenticationBackend {
static private $_registry = array();
static function _register($class) {
static::$_registry[$class::$id] = $class;
}
static function allRegistered() {
return array_merge(self::$_registry, parent::allRegistered());
}
function isBackendAllowed($staff, $bk) {
if (!($backends=self::getAllowedBackends($staff->getId())))
return true; //No restrictions
return in_array($bk::$id, array_map('strtolower', $backends));
}
function getAllowedBackends($userid) {
$backends =array();
//XXX: Only one backend can be specified at the moment.
$sql = 'SELECT backend FROM '.STAFF_TABLE
.' WHERE backend IS NOT NULL ';
if (is_numeric($userid))
$sql.= ' AND staff_id='.db_input($userid);
else {
$sql.= ' AND (username='.db_input($userid) .' OR email='.db_input($userid).')';
}
if (($res=db_query($sql, false)) && db_num_rows($res))
$backends[] = db_result($res);
return array_filter($backends);
}
function login($staff, $bk) {
global $ost;
if (!$bk || !($staff instanceof Staff))
return false;
// Ensure staff is allowed for realz to be authenticated via the backend.
if (!static::isBackendAllowed($staff, $bk)
|| !($authkey=$bk->getAuthKey($staff)))
return false;
//Log debug info.
$ost->logDebug(_S('Agent Login'),
sprintf(_S("%s logged in [%s], via %s"), $staff->getUserName(),
$_SERVER['REMOTE_ADDR'], get_class($bk))); //Debug.
$type = array('type' => 'login', 'data' => array('id' => $staff->getId(), 'name' => $staff->getName()->name));
Signal::send('staff.login', Staff::lookup($staff->getId()), $type);
// Tag the authkey.
$authkey = $bk::$id.':'.$authkey;
// Now set session crap and lets roll baby!
$authsession = &$_SESSION['_auth']['staff'];
$authsession = array(); //clear.
$authsession['id'] = $staff->getId();
$authsession['key'] = $authkey;
$staff->setAuthKey($authkey);
$staff->refreshSession(true); //set the hash.
Signal::send('auth.login.succeeded', $staff);
if ($bk->supportsInteractiveAuthentication())
$staff->cancelResetTokens();
// Update last-used language, login time, etc
$staff->onLogin($bk);
return true;
}
/* Base signOut
*
* Backend should extend the signout and perform any additional signout
* it requires.
*/
static function signOut($staff) {
global $ost;
$_SESSION['_auth']['staff'] = array();
unset($_SESSION[':token']['staff']);
$ost->logDebug(_S('Agent logout'),
sprintf(_S("%s logged out [%s]"),
$staff->getUserName(),
$_SERVER['REMOTE_ADDR'])); //Debug.
$type = array('type' => 'logout', 'data' => array('id' => $staff->getId(), 'name' => $staff->getName()->name));
Signal::send('staff.logout', Staff::lookup($staff->getId()), $type);
Signal::send('auth.logout', $staff);
}
// Called to get authenticated user (if any)
static function getUser() {
if (!isset($_SESSION['_auth']['staff'])
|| !$_SESSION['_auth']['staff']['key'])
return null;
list($id, $auth) = explode(':', $_SESSION['_auth']['staff']['key']);
if (!($bk=static::getBackend($id)) //get the backend
|| !($staff = $bk->validate($auth)) //Get AuthicatedUser
|| !($staff instanceof Staff)
|| $staff->getId() != $_SESSION['_auth']['staff']['id'] // check ID
)
return null;
$staff->setAuthKey($_SESSION['_auth']['staff']['key']);
return $staff;
}
function authenticate($username, $password) {
return false;
}
// Generic authentication key for staff's backend is the username
protected function getAuthKey($staff) {
if(!($staff instanceof Staff))
return null;
return $staff->getUsername();
}
protected function validate($authkey) {
if (($staff = StaffSession::lookup($authkey)) && $staff->getId())
return $staff;
}
}
abstract class ExternalStaffAuthenticationBackend
extends StaffAuthenticationBackend
implements ExternalAuthentication {
static $fa_icon = "signin";
static $sign_in_image_url = false;
static $service_name = "External";
function renderExternalLink() { ?>
<a class="external-sign-in" title="Sign in with <?php echo static::$service_name; ?>"
href="login.php?do=ext&bk=<?php echo urlencode(static::$id); ?>">
<?php if (static::$sign_in_image_url) { ?>
<img class="sign-in-image" src="<?php echo static::$sign_in_image_url;
?>" alt="Sign in with <?php echo static::$service_name; ?>"/>
<?php } else { ?>
<div class="external-auth-box">
<span class="external-auth-icon">
<i class="icon-<?php echo static::$fa_icon; ?> icon-large icon-fixed-with"></i>
</span>
<span class="external-auth-name">
Sign in with <?php echo static::$service_name; ?>
</span>
</div>
<?php } ?>
</a><?php
}
function triggerAuth() {
$_SESSION['ext:bk:class'] = get_class($this);
}
}
Signal::connect('api', function($dispatcher) {
$dispatcher->append(
url('^/auth/ext$', function() {
if ($class = $_SESSION['ext:bk:class']) {
$bk = StaffAuthenticationBackend::getBackend($class::$id)
?: UserAuthenticationBackend::getBackend($class::$id);
if ($bk instanceof ExternalAuthentication)
$bk->triggerAuth();
}
})
);
});
abstract class UserAuthenticationBackend extends AuthenticationBackend {
static private $_registry = array();
static function _register($class) {
static::$_registry[$class::$id] = $class;
}
static function allRegistered() {
return array_merge(self::$_registry, parent::allRegistered());
}
function getAllowedBackends($userid) {
$backends = array();
$sql = 'SELECT A1.backend FROM '.USER_ACCOUNT_TABLE
.' A1 INNER JOIN '.USER_EMAIL_TABLE.' A2 ON (A2.user_id = A1.user_id)'
.' WHERE backend IS NOT NULL '
.' AND (A1.username='.db_input($userid)
.' OR A2.`address`='.db_input($userid).')';
if (!($res=db_query($sql, false)))
return $backends;
while (list($bk) = db_fetch_row($res))
$backends[] = $bk;
return array_filter($backends);
}
function login($user, $bk) {
global $ost;
if (!$user || !$bk
|| !$bk::$id //Must have ID
|| !($authkey = $bk->getAuthKey($user)))
return false;
$acct = $user->getAccount();
if ($acct) {
if (!$acct->isConfirmed())
throw new AccessDenied(__('Account confirmation required'));
elseif ($acct->isLocked())
throw new AccessDenied(__('Account is administratively locked'));
}
// Tag the user and associated ticket in the SESSION
$this->setAuthKey($user, $bk, $authkey);
//The backend used decides the format of the auth key.
// XXX: encrypt to hide the bk??
$user->setAuthKey($authkey);
$user->refreshSession(true); //set the hash.
//Log login info...
$msg=sprintf(_S('%1$s (%2$s) logged in [%3$s]'
/* Tokens are <username>, <id>, and <ip> */),
$user->getUserName(), $user->getId(), $_SERVER['REMOTE_ADDR']);
$ost->logDebug(_S('User login'), $msg);
$type = array('type' => 'login', 'data' => array('id' => $user->getId(), 'name' => $user->getName()->name));
Signal::send('user.login', User::lookup($user->getId()), $type);
if ($bk->supportsInteractiveAuthentication() && ($acct=$user->getAccount()))
$acct->cancelResetTokens();
// Update last-used language, login time, etc
$user->onLogin($bk);
return true;
}
function setAuthKey($user, $bk, $key=false) {
$authkey = $key ?: $bk->getAuthKey($user);
//Tag the authkey.
$authkey = $bk::$id.':'.$authkey;
//Set the session goodies
$authsession = &$_SESSION['_auth']['user'];
$authsession = array(); //clear.
$authsession['id'] = $user->getId();
$authsession['key'] = $authkey;
}
function authenticate($username, $password) {
return false;
}
static function signOut($user) {
global $ost;
$_SESSION['_auth']['user'] = array();
unset($_SESSION[':token']['client']);
$ost->logDebug(_S('User logout'),
sprintf(_S("%s logged out [%s]" /* Tokens are <username> and <ip> */),
$user->getUserName(), $_SERVER['REMOTE_ADDR']));
$type = array('type' => 'logout', 'data' => array('id' => $user->getId(), 'name' => $user->getName()->name));
Signal::send('user.logout', User::lookup($user->getId()), $type);
}
protected function getAuthKey($user) {
return $user->getId();
}
static function getUser() {
if (!isset($_SESSION['_auth']['user'])
|| !$_SESSION['_auth']['user']['key'])
return null;
list($id, $auth) = explode(':', $_SESSION['_auth']['user']['key']);
if (!($bk=static::getBackend($id)) //get the backend
|| !($user=$bk->validate($auth)) //Get AuthicatedUser
|| !($user instanceof AuthenticatedUser) // Make sure it user
|| $user->getId() != $_SESSION['_auth']['user']['id'] // check ID
)
return null;
$user->setAuthKey($_SESSION['_auth']['user']['key']);
return $user;
}
protected function validate($userid) {
if (!($user = User::lookup($userid)))
return false;
elseif (!$user->getAccount())
return false;
return new ClientSession(new EndUser($user));
}
}
abstract class ExternalUserAuthenticationBackend
extends UserAuthenticationBackend
implements ExternalAuthentication {
static $fa_icon = "signin";
static $sign_in_image_url = false;
static $service_name = "External";
function renderExternalLink() { ?>
<a class="external-sign-in" title="<?php echo sprintf(__('Sign in with %s'), __(static::$service_name)); ?>"
href="login.php?do=ext&bk=<?php echo urlencode(static::$id); ?>">
<?php if (static::$sign_in_image_url) { ?>
<img class="sign-in-image" src="<?php echo static::$sign_in_image_url;
?>" alt="<?php echo sprintf(__('Sign in with %s'), __(static::$service_name)); ?>"/>
<?php } else { ?>
<div class="external-auth-box">
<span class="external-auth-icon">
<i class="icon-<?php echo static::$fa_icon; ?> icon-large icon-fixed-with"></i>
</span>
<span class="external-auth-name">
<?php echo sprintf(__('Sign in with %s'), __(static::$service_name)); ?>
</span>
</div>
<?php } ?>
</a><?php
}
function triggerAuth() {
$_SESSION['ext:bk:class'] = get_class($this);
}
}
/**
* This will be an exception in later versions of PHP
*/
class AccessDenied extends Exception {
function __construct($reason) {
$this->reason = $reason;
parent::__construct($reason);
}
}
/**
* Simple authentication backend which will lock the login form after a
* configurable number of attempts
*/
abstract class AuthStrikeBackend extends AuthenticationBackend {
function authenticate($username, $password=null) {
return static::authTimeout();
}
function signOn() {
return static::authTimeout();
}
static function signOut($user) {
return false;
}
function login($user, $bk) {
return false;
}
static function getUser() {
return null;
}
function supportsInteractiveAuthentication() {
return false;
}
function getAllowedBackends($userid) {
return array();
}
function getAuthKey($user) {
return null;
}
//Provides audit facility for logins attempts
function audit($result, $credentials) {
//Count failed login attempts as a strike.
if ($result instanceof AccessDenied)
return static::authStrike($credentials);
}
abstract function authStrike($credentials);
abstract function authTimeout();
}
/*
* Backend to monitor staff's failed login attempts
*/
class StaffAuthStrikeBackend extends AuthStrikeBackend {
function authTimeout() {
global $ost;
$cfg = $ost->getConfig();
$authsession = &$_SESSION['_auth']['staff'];
if (!$authsession['laststrike'])
return;
//Veto login due to excessive login attempts.
if((time()-$authsession['laststrike'])<$cfg->getStaffLoginTimeout()) {
$authsession['laststrike'] = time(); //reset timer.
return new AccessDenied(__('Maximum failed login attempts reached'));
}
//Timeout is over.
//Reset the counter for next round of attempts after the timeout.
$authsession['laststrike']=null;
$authsession['strikes']=0;
}
function authstrike($credentials) {
global $ost;
$cfg = $ost->getConfig();
$authsession = &$_SESSION['_auth']['staff'];
$username = $credentials['username'];
$authsession['strikes']+=1;
if($authsession['strikes']>$cfg->getStaffMaxLogins()) {
$authsession['laststrike']=time();
$timeout = $cfg->getStaffLoginTimeout()/60;
$alert=_S('Excessive login attempts by an agent?')."\n"
._S('Username').": $username\n"
._S('IP').": {$_SERVER['REMOTE_ADDR']}\n"
._S('Time').": ".date('M j, Y, g:i a T')."\n\n"
._S('Attempts').": {$authsession['strikes']}\n"
._S('Timeout').": ".sprintf(_N('%d minute', '%d minutes', $timeout), $timeout)."\n\n";
$admin_alert = ($cfg->alertONLoginError() == 1) ? TRUE : FALSE;
$ost->logWarning(sprintf(_S('Excessive login attempts (%s)'),$username),
$alert, $admin_alert);
if ($username) {
$staffId = Staff::objects()->filter(array('username'=>$username))->values_flat('staff_id')->first();
if ($staffId)
$staff = Staff::lookup($staffId[0]);
if ($staff) {
$type = array('type' => 'login',
'data' => array('id' => $staff->getId(), 'name' => $staff->getName()->name,
'msg' => 'Excessive login attempts (' . $authsession['strikes'] . ')'));
Signal::send('staff.login', Staff::lookup($staff->getId()), $type);
}
}
return new AccessDenied(__('Forgot your login info? Contact Admin.'));
//Log every other third failed login attempt as a warning.
} elseif($authsession['strikes']%3==0) {
$alert=_S('Username').": {$username}\n"
._S('IP').": {$_SERVER['REMOTE_ADDR']}\n"
._S('Time').": ".date('M j, Y, g:i a T')."\n\n"
._S('Attempts').": {$authsession['strikes']}";
$ost->logWarning(sprintf(_S('Failed agent login attempt (%s)'),$username),
$alert, false);
}
}
}
StaffAuthenticationBackend::register('StaffAuthStrikeBackend');
/*
* Backend to monitor user's failed login attempts
*/
class UserAuthStrikeBackend extends AuthStrikeBackend {
function authTimeout() {
global $ost;
$cfg = $ost->getConfig();
$authsession = &$_SESSION['_auth']['user'];
if (!$authsession['laststrike'])
return;
//Veto login due to excessive login attempts.
if ((time()-$authsession['laststrike']) < $cfg->getStaffLoginTimeout()) {
$authsession['laststrike'] = time(); //reset timer.
return new AccessDenied(__("You've reached maximum failed login attempts allowed."));
}
//Timeout is over.
//Reset the counter for next round of attempts after the timeout.
$authsession['laststrike']=null;
$authsession['strikes']=0;
}
function authstrike($credentials) {
global $ost;
$cfg = $ost->getConfig();
$authsession = &$_SESSION['_auth']['user'];
$username = $credentials['username'];
$password = $credentials['password'];
$authsession['strikes']+=1;
if($authsession['strikes']>$cfg->getClientMaxLogins()) {
$authsession['laststrike'] = time();
$alert=_S('Excessive login attempts by a user.')."\n".
_S('Username').": {$username}\n".
_S('IP').": {$_SERVER['REMOTE_ADDR']}\n".
_S('Time').": ".date('M j, Y, g:i a T')."\n\n".
_S('Attempts').": {$authsession['strikes']}";
$admin_alert = ($cfg->alertONLoginError() == 1 ? TRUE : FALSE);
$ost->logError(_S('Excessive login attempts (user)'), $alert, $admin_alert);
if ($username) {
$account = UserAccount::lookupByUsername($username);
$id = UserEmailModel::getIdByEmail($username);
if ($account)
$user = User::lookup($account->user_id);
elseif ($id)
$user = User::lookup($id);
if ($user) {
$type = array('type' => 'login',
'data' => array('id' => $user->getId(), 'name' => $user->getName()->name,
'msg' => 'Excessive login attempts (' . $authsession['strikes'] . ')'));
Signal::send('user.login', User::lookup($user->getId()), $type);
}
}
return new AccessDenied(__('Access denied'));
} elseif($authsession['strikes']%3==0) { //Log every third failed login attempt as a warning.
$alert=_S('Username').": {$username}\n".
_S('IP').": {$_SERVER['REMOTE_ADDR']}\n".
_S('Time').": ".date('M j, Y, g:i a T')."\n\n".
_S('Attempts').": {$authsession['strikes']}";
$ost->logWarning(_S('Failed login attempt (user)'), $alert, false);