-
Notifications
You must be signed in to change notification settings - Fork 24
/
RealMeService.php
1263 lines (1088 loc) · 48 KB
/
RealMeService.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
namespace SilverStripe\RealMe;
use DOMDocument;
use DOMNodeList;
use Exception as BaseException;
use InvalidArgumentException;
use OneLogin\Saml2\Auth;
use OneLogin\Saml2\Error;
use OneLogin\Saml2\Response;
use OneLogin\Saml2\Utils;
use Psr\Log\LoggerInterface;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Environment;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\RealMe\Exception as RealMeException;
use SilverStripe\RealMe\Model\FederatedIdentity;
use SilverStripe\RealMe\Model\User;
use SilverStripe\Security\Member;
use SilverStripe\Security\Security;
use SilverStripe\View\TemplateGlobalProvider;
class RealMeService implements TemplateGlobalProvider
{
use Configurable, Injectable;
/**
* Current RealMe supported environments.
*/
const ENV_MTS = 'mts';
const ENV_ITE = 'ite';
const ENV_PROD = 'prod';
/**
* SAML binding types
*/
const TYPE_LOGIN = 'login';
const TYPE_ASSERT = 'assert';
/**
* the valid AuthN context values for each supported RealMe environment.
*/
const AUTHN_LOW_STRENGTH = 'urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:LowStrength';
const AUTHN_MOD_STRENTH = 'urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:ModStrength';
const AUTHN_MOD_MOBILE_SMS =
'urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:ModStrength::OTP:Mobile:SMS';
const AUTHN_MOD_TOKEN_SID =
'urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:ModStrength::OTP:Token:SID';
/**
* Realme SAML2 error status constants
*/
const ERR_TIMEOUT = 'urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:status:Timeout';
const ERR_INTERNAL_ERROR = 'urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:status:InternalError';
/**
* SAML2 Error constants used for business logic and switching error messages
*/
const ERR_AUTHN_FAILED = 'urn:oasis:names:tc:SAML:2.0:status:AuthnFailed';
const ERR_UNKNOWN_PRINCIPAL = 'urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal';
const ERR_NO_AVAILABLE_IDP = 'urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP';
const ERR_NO_PASSIVE = 'urn:oasis:names:tc:SAML:2.0:status:NoPassive';
const ERR_NO_AUTHN_CONTEXT = 'urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext';
const ERR_REQUEST_UNSUPPORTED = 'urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported';
const ERR_REQUEST_DENIED = 'urn:oasis:names:tc:SAML:2.0:status:RequestDenied';
const ERR_UNSUPPORTED_BINDING = 'urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding';
/**
* @var bool true to sync RealMe data and create/update local {@link Member} objects upon successful authentication
* @config
*/
private static $sync_with_local_member_database = false;
/**
* @var User|null User data returned by RealMe. Provided by {@link self::ensureLogin()}.
*
* Data within this ArrayData is as follows:
* - NameID: ArrayData Includes the UserFlt and associated formatting information
* - UserFlt: string RealMe pseudonymous username / identity
* - Attributes: ArrayData User attributes returned by RealMe
* - Expire: SS_Datetime The expiry date & time of this authentication session
* - SessionIndex: string Unique identifier used to identify a user with both IdP and SP for given user.
*/
private static $user_data = null;
/**
* @config
* @var string The RealMe environment to connect to and authenticate against. This should be set by Config, and
* generally be different per SilverStripe environment (e.g. developer environments would generally use 'mts',
* UAT/staging sites might use 'ite', and production sites would use 'prod'.
*
* Valid options:
* - mts
* - ite
* - prod
*/
private static $realme_env = 'mts';
/**
* @var array The RealMe environments that can be configured for use with this module.
*/
private static $allowed_realme_environments = array(self::ENV_MTS, self::ENV_ITE, self::ENV_PROD);
/**
* @config
* @var string The RealMe integration type to use when connecting to RealMe. After successful authentication:
* - 'login' provides a unique FLT (Federated Login Token) back
* - 'assert' provides a unique FIT (Federated Identity Token) and a {@link RealMeFederatedIdentity} object back
*/
private static $integration_type = 'login';
private static $allowed_realme_integration_types = array(self::TYPE_LOGIN, self::TYPE_ASSERT);
/**
* @config
* @var array Stores the entity ID value for each supported RealMe environment. This needs to be setup prior to
* running the `RealMeSetupTask` build task. For more information, see the module documentation. An entity ID takes
* the form of a URL, e.g. https://www.agency.govt.nz/privacy-realm-name/application-name
*/
private static $sp_entity_ids = array(
self::ENV_MTS => null,
self::ENV_ITE => null,
self::ENV_PROD => null
);
/**
* @config
* @var array Stores the default identity provider (IdP) entity IDs. These can be customised if you're using an
* intermediary IdP instead of connecting to RealMe directly.
*/
private static $idp_entity_ids = array(
self::ENV_MTS => array(
self::TYPE_LOGIN => 'https://login.mts.realme.govt.nz/4af8e0e0-497b-4f52-805c-00fa09b50c16' .
'/B2C_1A_DIA_RealMe_MTSLoginService',
self::TYPE_ASSERT => 'https://login.mts.realme.govt.nz/4af8e0e0-497b-4f52-805c-00fa09b50c16' .
'/B2C_1A_DIA_RealMe_MTSAssertionService'
),
self::ENV_ITE => array(
self::TYPE_LOGIN => 'https://login.ite.realme.govt.nz/12c36372-4b2d-4865-b1d1-9599b0d37348' .
'/B2C_1A_DIA_RealMe_LoginService',
self::TYPE_ASSERT => 'https://login.ite.realme.govt.nz/12c36372-4b2d-4865-b1d1-9599b0d37348' .
'/B2C_1A_DIA_RealMe_AssertionService'
),
self::ENV_PROD => array(
self::TYPE_LOGIN => 'https://login.realme.govt.nz/32179062-92f6-4eb0-89bc-df400a9e0367' .
'/B2C_1A_DIA_RealMe_LoginService',
self::TYPE_ASSERT => 'https://login.realme.govt.nz/32179062-92f6-4eb0-89bc-df400a9e0367' .
'/B2C_1A_DIA_RealMe_AssertionService',
)
);
private static $idp_sso_service_urls = array(
self::ENV_MTS => array(
self::TYPE_LOGIN => 'https://login.mts.realme.govt.nz/b2cdiamts01rmpubdir.onmicrosoft.com' .
'/B2C_1A_DIA_RealMe_MTSLoginService/samlp/sso/login',
self::TYPE_ASSERT => 'https://login.mts.realme.govt.nz/b2cdiamts01rmpubdir.onmicrosoft.com' .
'/B2C_1A_DIA_RealMe_MTSAssertionService/samlp/sso/login'
),
self::ENV_ITE => array(
self::TYPE_LOGIN => 'https://login.ite.realme.govt.nz/b2cdiaite01rmpubdir.onmicrosoft.com' .
'/B2C_1A_DIA_RealMe_LoginService/samlp/sso/login',
self::TYPE_ASSERT => 'https://login.ite.realme.govt.nz/b2cdiaite01rmpubdir.onmicrosoft.com' .
'/B2C_1A_DIA_RealMe_AssertionService/samlp/sso/login'
),
self::ENV_PROD => array(
self::TYPE_LOGIN => 'https://login.realme.govt.nz/32179062-92f6-4eb0-89bc-df400a9e0367' .
'/B2C_1A_DIA_RealMe_LoginService/samlp/sso/login',
self::TYPE_ASSERT => 'https://login.realme.govt.nz/32179062-92f6-4eb0-89bc-df400a9e0367' .
'/B2C_1A_DIA_RealMe_AssertionService/samlp/sso/login'
)
);
/**
* @var array A list of certificate filenames for different RealMe environments and integration types. These files
* must be located in the directory specified by the REALME_CERT_DIR environment variable. These filenames used to
* be the same as the files as found on the RealMe Developers website, within the 'Integration Bundle' ZIP files
* for the different environments (MTS, ITE and Production), however these filenames are now very generic so there
* is documentation in the README to ensure the filenames are configured correctly for the various environments.
*/
private static $idp_x509_cert_filenames = array(
self::ENV_MTS => array(
self::TYPE_LOGIN => 'mts_login_saml_idp.cer',
self::TYPE_ASSERT => 'mts_assert_saml_idp.cer'
),
// As of the 2021 Azure re-platforming, ITE certificates are the same - a single cert for both logon & assert
self::ENV_ITE => array(
self::TYPE_LOGIN => 'ite.signing.logon.realme.govt.nz.cer',
self::TYPE_ASSERT => 'ite.signing.logon.realme.govt.nz.cer'
),
// As of the 2021 Azure re-platforming, prod certificates are the same - a single cert for both logon & assert
self::ENV_PROD => array(
self::TYPE_LOGIN => 'signing.realme.govt.nz.cer',
self::TYPE_ASSERT => 'signing.realme.govt.nz.cer'
)
);
/**
* @config
* @var array Stores the AuthN context values for each supported RealMe environment. This needs to be setup prior to
* running the `RealMeSetupTask` build task. For more information, see the module documentation. An AuthN context
* can be one of the following:
*
* Username and password only:
* - urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:LowStrength
*
* Username, password, and any moderate strength second level of authenticator (RSA token, Google Auth, SMS)
* - urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:ModStrength
*
* The following two are less often used, and shouldn't be used unless there's a specific need.
*
* Username, password, and only SMS 2FA token
* - urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:ModStrength::OTP:Mobile:SMS
*
* Username, password, and only RSA 2FA token
* - urn:nzl:govt:ict:stds:authn:deployment:GLS:SAML:2.0:ac:classes:ModStrength::OTP:Token:SID
*/
private static $authn_contexts = array(
self::ENV_MTS => null,
self::ENV_ITE => null,
self::ENV_PROD => null
);
/**
* @config $allowed_authn_context_list
* @var $allowed_authn_context_list array
*
* A list of the valid authn context values supported for realme.
*/
private static $allowed_authn_context_list = array(
self::AUTHN_LOW_STRENGTH,
self::AUTHN_MOD_STRENTH,
self::AUTHN_MOD_MOBILE_SMS,
self::AUTHN_MOD_TOKEN_SID
);
/**
* @config
* @var array Domain names for metadata files. Used in @link RealMeSetupTask when outputting metadata XML
*/
private static $metadata_assertion_service_domains = array(
self::ENV_MTS => null,
self::ENV_ITE => null,
self::ENV_PROD => null
);
/**
* @config
* @var array A list of error messages to display if RealMe returns error statuses, instead of the default
* translations (found in realme/lang/en.yml for example).
*/
private static $realme_error_message_overrides = array(
self::ERR_AUTHN_FAILED => null,
self::ERR_TIMEOUT => null,
self::ERR_INTERNAL_ERROR => null,
self::ERR_NO_AVAILABLE_IDP => null,
self::ERR_REQUEST_UNSUPPORTED => null,
self::ERR_NO_PASSIVE => null,
self::ERR_REQUEST_DENIED => null,
self::ERR_UNSUPPORTED_BINDING => null,
self::ERR_UNKNOWN_PRINCIPAL => null,
self::ERR_NO_AUTHN_CONTEXT => null
);
/**
* @config
* @var string|null The organisation name to be used in metadata XML that is submitted to RealMe
*/
private static $metadata_organisation_name = null;
/**
* @config
* @var string|null The organisation display name to be used in metadata XML that is submitted to RealMe
*/
private static $metadata_organisation_display_name = null;
/**
* @config
* @var string|null The organisation URL to be used in metadata XML that is submitted to RealMe
*/
private static $metadata_organisation_url = null;
/**
* @config
* @var string|null The support contact's company name to be used in metadata XML that is submitted to RealMe
*/
private static $metadata_contact_support_company = null;
/**
* @config
* @var string|null The support contact's first name(s) to be used in metadata XML that is submitted to RealMe
*/
private static $metadata_contact_support_firstnames = null;
/**
* @config
* @var string|null The support contact's surname to be used in metadata XML that is submitted to RealMe
*/
private static $metadata_contact_support_surname = null;
/**
* @var Auth|null Set by {@link getAuth()}, which creates an instance of Auth to check
* authentication against
*/
private $auth = null;
/**
* @var string|null The last error message during login enforcement
*/
private $lastError = null;
/**
* @return array
*/
public static function get_template_global_variables()
{
return array(
'RealMeUser' => array(
'method' => 'current_realme_user'
)
);
}
/**
* @return HTTPRequest|null
*/
protected static function getRequest()
{
if (!Injector::inst()->has(HTTPRequest::class)) {
return null;
};
return Injector::inst()->get(HTTPRequest::class);
}
/**
* Return the user data which was saved to session from the first RealMe
* auth.
* Note: Does not check authenticity or expiry of this data
*
* @param HTTPRequest $request
* @return User
*/
public static function user_data()
{
if (!is_null(static::$user_data)) {
return static::$user_data;
}
$request = self::getRequest();
if (!$request) {
return null;
}
$sessionData = $request->getSession()->get('RealMe.SessionData');
// Exit point
if (is_null($sessionData)) {
return null;
}
// Unserialise stored data
$user = unserialize($sessionData ?? '');
if ($user == false || !$user instanceof User) {
return null;
}
static::$user_data = $user;
return static::$user_data;
}
public function getUserData()
{
return static::user_data();
}
/**
* Calls available user data and checks for validity
*
* @return User
*/
public static function current_realme_user()
{
$user = self::user_data();
if ($user && !$user->isValid()) {
return null;
}
return $user;
}
/**
* A helpful static method that follows SilverStripe naming for Member::currentUser();
*
* @return User
*/
public static function currentRealMeUser()
{
return self::current_realme_user();
}
/**
* Enforce login via RealMe. This can be used in controllers to force users to be authenticated via RealMe (not
* necessarily logged in as a {@link Member}), in the form of:
* <code>
* Session::set('RealMeBackURL', '/path/to/the/controller/method');
* if($service->enforceLogin()) {
* // User has a valid RealMe account, $service->getAuthData() will return you their details
* } else {
* // Something went wrong processing their details, show an error
* }
* </code>
*
* In cases where people are *not* authenticated with RealMe, this method will redirect them directly to RealMe.
*
* However, generally you want this to be an explicit process, so you should look at instead using the standard
* {@link RealMeAuthenticator}.
*
* A return value of bool false indicates that there was a failure during the authentication process (perhaps a
* communication issue, or a failure to decode the response correctly. You should handle this like you would any
* other unexpected authentication error. You can use {@link getLastError()} to see if a human-readable error
* message exists for display to the user.
*
* @param HTTPRequest $request
* @param string $backUrl
* @return bool|null true if the user is correctly authenticated, false if there was an error with login
* @throws Error
*/
public function enforceLogin(HTTPRequest $request, $backUrl = null)
{
// First, check to see if we have an existing authenticated session
if ($this->isAuthenticated()) {
return true;
}
$session = $request->getSession();
if ($backUrl) {
$session->set('RealMeBackURL', $this->validSiteURL($backUrl));
} else {
$backUrl = $this->getBackURL($request);
}
$backUrl = $this->validSiteURL($backUrl);
if (!$backUrl) {
$backUrl = Director::absoluteBaseURL();
}
// If not, attempt to retrieve authentication data from OneLogin (in case this is called during SAML assertion)
try {
if (!$session->get("RealMeErrorBackURL") && Controller::has_curr()) {
$session->set("RealMeErrorBackURL", Controller::curr()->Link("Login"));
}
$auth = $this->getAuth();
$auth->processResponse();
// if there were any errors from the SAML request, process and translate them.
$errors = $auth->getErrors();
if (is_array($errors) && !empty($errors)) {
$this->processSamlErrors($errors);
return false;
}
$authData = $this->getAuthData();
// If no data is found, then force login
if (is_null($authData)) {
throw new RealMeException('No SAML data, enforcing login', RealMeException::NOT_AUTHENTICATED);
}
// call a success method as we've successfully logged in (if it exists)
Member::singleton()->extend('onRealMeLoginSuccess', $authData);
} catch (BaseException $e) {
Member::singleton()->extend("onRealMeLoginFailure", $e);
// No auth data or failed to decrypt, enforce login again
$this->getAuth()->login($backUrl);
die;
}
return $auth->isAuthenticated();
}
/**
* If there was an error returned from the saml response, process the errors
*
* @param $errors
*/
private function processSamlErrors(array $errors)
{
$translatedMessage = null;
// The error message returned by onelogin/php-saml is the top-level error, but we want the actual error
$request = Controller::curr()->getRequest();
if ($request->isPOST() && $request->postVar("SAMLResponse")) {
$response = new Response($this->getAuth()->getSettings(), $request->postVar("SAMLResponse"));
$internalError = Utils::query(
$response->document,
"/samlp:Response/samlp:Status/samlp:StatusCode/samlp:StatusCode/@Value"
);
if ($internalError instanceof DOMNodeList && $internalError->length > 0) {
$internalErrorCode = $internalError->item(0)->textContent;
$translatedMessage = $this->findErrorMessageForCode($internalErrorCode);
}
}
// If we found a message to display, then let's redirect to the form and display it
if ($translatedMessage) {
$this->lastError = $translatedMessage;
}
Injector::inst()->get(LoggerInterface::class)->info(sprintf(
'onelogin/php-saml error messages: %s (%s)',
join(', ', $errors),
$this->getAuth()->getLastErrorReason()
));
}
/**
* Checks data stored in Session to see if the user is authenticated.
* @return bool true if the user is authenticated via RealMe and we can trust ->getUserData()
*/
public function isAuthenticated()
{
$user = $this->getUserData();
return $user instanceof User && $user->isAuthenticated();
}
/**
* Returns a {@link RealMeUser} object if one can be built from the RealMe session data.
*
* @throws Error Passes on the SAML error if it's not indicating a lack of SAML response data
* @throws RealMeException If identity information exists but couldn't be decoded, or doesn't exist
* @return User|null
*/
public function getAuthData()
{
// returns null if the current auth is invalid or timed out.
try {
// Process response and capture details
$auth = $this->getAuth();
if (!$auth->isAuthenticated()) {
throw new RealMeException(
'OneLogin SAML library did not successfully authenticate, but did not return a specific error',
RealMeException::NOT_AUTHENTICATED
);
}
$spNameId = $auth->getNameId();
if (!is_string($spNameId)) {
throw new RealMeException('Invalid/Missing NameID in SAML response', RealMeException::MISSING_NAMEID);
}
$sessionIndex = $auth->getSessionIndex();
if (!is_string($sessionIndex)) {
throw new RealMeException(
'Invalid/Missing SessionIndex value in SAML response',
RealMeException::MISSING_SESSION_INDEX
);
}
$attributes = $auth->getAttributes();
if (!is_array($attributes)) {
throw new RealMeException(
'Invalid/Missing attributes array in SAML response',
RealMeException::MISSING_ATTRIBUTES
);
}
$federatedIdentity = $this->retrieveFederatedIdentity($auth);
// We will have either a FLT or FIT, depending on integration type
if ($this->config()->integration_type == self::TYPE_ASSERT) {
$userTag = $this->retrieveFederatedIdentityTag($auth);
} else {
$userTag = $this->retrieveFederatedLogonTag($auth);
}
return User::create([
'SPNameID' => $spNameId,
'UserFederatedTag' => $userTag,
'SessionIndex' => $sessionIndex,
'Attributes' => $attributes,
'FederatedIdentity' => $federatedIdentity,
]);
} catch (Error $e) {
// If the Exception code indicates there wasn't a response, we ignore it as it simply means the visitor
// isn't authenticated yet. Otherwise, we re-throw the Exception
if ($e->getCode() === Error::SAML_RESPONSE_NOT_FOUND) {
return null;
} else {
throw $e;
}
}
}
/**
* Clear the RealMe credentials from Session, called during Security->logout() overrides
*
* @param HTTPRequest $request
* @return void
*/
public function clearLogin(HTTPRequest $request)
{
$this->config()->__set('user_data', null);
$session = $request->getSession();
$session->set("RealMeBackURL", null);
$session->set("RealMeErrorBackURL", null);
$session->set("RealMe.SessionData", null);
$session->set("RealMe.OriginalResponse", null);
$session->set("RealMe.LastErrorMessage", null);
}
public function getLastError()
{
return $this->lastError;
}
/**
* @return string A BackURL as specified originally when accessing /Security/login, for use after authentication
*/
public function getBackURL(HTTPRequest $request)
{
$url = null;
$session = $request->getSession();
if ($session->get('RealMeBackURL')) {
$url = $session->get('RealMeBackURL');
$session->clear('RealMeBackURL'); // Ensure we don't redirect back to the same error twice
} elseif ($request->requestVar('BackURL')) {
$url = $request->requestVar('BackURL');
} elseif ($request->postVar('RelayState')) {
$url = $request->postVar('RelayState');
}
return $this->validSiteURL($url);
}
public function getErrorBackURL(HTTPRequest $request)
{
$url = null;
$session = $request->getSession();
if ($session->get('RealMeErrorBackURL')) {
$url = $session->get('RealMeErrorBackURL');
$session->clear('RealMeErrorBackURL'); // Ensure we don't redirect back to the same error twice
}
return $this->validSiteURL($url);
}
private function validSiteURL($url = null)
{
if (isset($url) && Director::is_site_url($url)) {
$url = Director::absoluteURL($url);
} else {
// Spoofing attack or no back URL set, redirect to homepage instead of spoofing url
$url = Director::absoluteBaseURL();
}
return $url;
}
/**
* @param String $subdir A sub-directory where certificates may be stored for
* a specific case
* @return string|null Either the directory where certificates are stored,
* or null if undefined
*/
public function getCertDir($subdir = null)
{
// Trim prepended seprator to avoid absolute path
$path = ltrim(ltrim($subdir ?? '', '/'), '\\');
if ($certDir = Environment::getEnv('REALME_CERT_DIR')) {
$path = $certDir . '/' . $path; // Duplicate slashes will be handled by realpath()
}
return realpath($path ?? '');
}
/**
* Returns the appropriate AuthN Context, given the environment passed in. The AuthNContext may be different per
* environment, and should be one of the strings as defined in the static {@link self::$authn_contexts} at the top
* of this class.
*
* @param string $env The environment to return the AuthNContext for. Must be one of the RealMe environment names
* @return string|null Returns the AuthNContext for the given $env, or null if no context exists
*/
public function getAuthnContextForEnvironment($env)
{
return $this->getConfigurationVarByEnv('authn_contexts', $env);
}
/**
* Returns the full path to the SAML signing certificate file, used by SimpleSAMLphp to sign all messages sent to
* RealMe.
*
* @return string|null Either the full path to the SAML signing certificate file, or null if it doesn't exist
*/
public function getSigningCertPath()
{
return $this->getCertPath('SIGNING');
}
public function getIdPCertPath()
{
$cfg = $this->config();
$name = $this->getConfigurationVarByEnv('idp_x509_cert_filenames', $cfg->realme_env, $cfg->integration_type);
return $this->getCertDir($name);
}
public function getSPCertContent($contentType = 'certificate')
{
return $this->getCertificateContents($this->getSigningCertPath(), $contentType);
}
public function getIdPCertContent()
{
return $this->getCertificateContents($this->getIdPCertPath());
}
/**
* Returns the content of the SAML signing certificate. This is used by getAuth() and by RealMeSetupTask to produce
* metadata XML files.
*
* @param string $certPath The filesystem path to where the certificate is stored on the filesystem
* @param string $contentType Either 'certificate' or 'key', depending on which part of the file to return
* @return string|null The content of the signing certificate
*/
public function getCertificateContents($certPath, $contentType = 'certificate')
{
$text = null;
if (!is_null($certPath)) {
$certificateContents = file_get_contents($certPath ?? '');
// If the file does not contain any header information and the content type is certificate, just return it
if ($contentType == 'certificate' && !preg_match('/-----BEGIN/', $certificateContents ?? '')) {
$text = $certificateContents;
} else {
// Otherwise, inspect the file and match based on the full contents
if ($contentType == 'certificate') {
$pattern = '/-----BEGIN CERTIFICATE-----[\r\n]*([^-]*)[\r\n]*-----END CERTIFICATE-----/';
} elseif ($contentType == 'key') {
$pattern = '/-----BEGIN [A-Z ]*PRIVATE KEY-----[\r\n]*([^-]*)[\r\n]*'
. '-----END [A-Z ]*PRIVATE KEY-----/';
} else {
throw new InvalidArgumentException('Argument contentType must be either "certificate" or "key"');
}
// This is a PEM key, and we need to extract just the certificate, stripping out the private key etc.
// So we search for everything between '-----BEGIN CERTIFICATE-----' and '-----END CERTIFICATE-----'
preg_match(
$pattern ?? '',
$certificateContents ?? '',
$matches
);
if (isset($matches) && is_array($matches) && isset($matches[1])) {
$text = trim($matches[1] ?? '');
}
}
}
return $text;
}
/**
* @param string $env The environment to return the entity ID for. Must be one of the RealMe environment names
* @return string|null Either the assertion consumer service location, or null if information doesn't exist
*/
public function getAssertionConsumerServiceUrlForEnvironment($env)
{
if (in_array($env, $this->getAllowedRealMeEnvironments() ?? []) === false) {
return null;
}
$domain = $this->getMetadataAssertionServiceDomainForEnvironment($env);
if (filter_var($domain, FILTER_VALIDATE_URL) === false) {
return null;
}
// Returns https://domain.govt.nz/Security/login/RealMe/acs
return Controller::join_links($domain, Security::config()->get('login_url'), 'RealMe/acs');
}
/**
* @return string|null The organisation name to be used in metadata XML output, or null if none exists
*/
public function getMetadataOrganisationName()
{
$orgName = $this->config()->metadata_organisation_name;
return (strlen($orgName ?? '') > 0) ? $orgName : null;
}
/**
* @return string|null The organisation display name to be used in metadata XML output, or null if none exists
*/
public function getMetadataOrganisationDisplayName()
{
$displayName = $this->config()->metadata_organisation_display_name;
return (strlen($displayName ?? '') > 0) ? $displayName : null;
}
/**
* @return string|null The organisation website URL to be used in metadata XML output, or null if none exists
*/
public function getMetadataOrganisationUrl()
{
$url = $this->config()->metadata_organisation_url;
return (strlen($url ?? '') > 0) ? $url: null;
}
/**
* @return string[] The support contact details to be used in metadata XML output, with null values if they don't
* exist
*/
public function getMetadataContactSupport()
{
$company = $this->config()->metadata_contact_support_company;
$firstNames = $this->config()->metadata_contact_support_firstnames;
$surname = $this->config()->metadata_contact_support_surname;
return array(
'company' => (strlen($company ?? '') > 0) ? $company : null,
'firstNames' => (strlen($firstNames ?? '') > 0) ? $firstNames : null,
'surname' => (strlen($surname ?? '') > 0) ? $surname : null
);
}
/**
* The list of RealMe environments that can be used. By default, we allow mts, ite and production.
* @return array
*/
public function getAllowedRealMeEnvironments()
{
return $this->config()->allowed_realme_environments;
}
/**
* The list of valid realme AuthNContexts
* @return array
*/
public function getAllowedAuthNContextList()
{
return $this->config()->allowed_authn_context_list;
}
/**
* Returns the appropriate entity ID for RealMe, given the environment passed in. The entity ID may be different per
* environment, and should be a full URL, including privacy realm and application name. For example, this may be:
* https://www.agency.govt.nz/privacy-realm-name/application-name
*
* @return string|null Returns the entity ID for the current environment, or null if no entity ID exists
*/
public function getSPEntityID()
{
return $this->getConfigurationVarByEnv('sp_entity_ids', $this->config()->realme_env);
}
private function getIdPEntityID()
{
$cfg = $this->config();
return $this->getConfigurationVarByEnv('idp_entity_ids', $cfg->realme_env, $cfg->integration_type);
}
private function getSingleSignOnServiceURL()
{
$cfg = $this->config();
return $this->getConfigurationVarByEnv('idp_sso_service_urls', $cfg->realme_env, $cfg->integration_type);
}
private function getRequestedAuthnContext()
{
return $this->getConfigurationVarByEnv('authn_contexts', $this->config()->realme_env);
}
/**
* Returns the internal {@link Auth} object against which visitors are authenticated.
*
* @return Auth
*/
public function getAuth(HTTPRequest $request = null)
{
if (isset($this->auth)) {
return $this->auth;
}
if (!$request) {
$request = self::getRequest();
if (!$request) {
throw new RealMeException('A request must be provided for session access');
}
}
// Ensure onelogin is using the correct host, protocol and port incase a proxy is involved
Utils::setSelfHost($request->getHeader('Host'));
Utils::setSelfProtocol($request->getScheme());
$port = null;
if (isset($_SERVER['HTTP_X_FORWARDED_PORT'])) {
$port = $_SERVER['HTTP_X_FORWARDED_PORT'];
} elseif (isset($_SERVER['SERVER_PORT'])) {
$port = $_SERVER['SERVER_PORT'];
}
if ($port) {
Utils::setSelfPort($port);
}
$settings = [
'strict' => true,
'debug' => false,
// Service Provider (this installation) configuration
'sp' => [
'entityId' => $this->getSPEntityID(),
'x509cert' => $this->getSPCertContent('certificate'),
'privateKey' => $this->getSPCertContent('key'),
// According to RealMe messaging spec, must always be transient for assert; is irrelevant for login
'NameIDFormat' => $this->getNameIdFormat(),
'assertionConsumerService' => [
'url' => $this->getAssertionConsumerServiceUrlForEnvironment($this->config()->realme_env),
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' // Always POST, not artifact binding
]
],
// RealMe Identity Provider configuration
'idp' => [
'entityId' => $this->getIdPEntityID(),
'x509cert' => $this->getIdPCertContent(),
'singleSignOnService' => [
'url' => $this->getSingleSignOnServiceURL(),
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
]
],
'security' => [
'signatureAlgorithm' => 'http://www.w3.org/2000/09/xmldsig#rsa-sha1',
'authnRequestsSigned' => true,
'wantAssertionsEncrypted' => true,
'wantAssertionsSigned' => true,
'requestedAuthnContext' => [
$this->getRequestedAuthnContext()
]
]
];
$this->auth = new Auth($settings);
return $this->auth;
}
/**
* @return string the required NameIDFormat to be included in metadata XML, based on the requested integration type
*/
public function getNameIdFormat()
{
switch ($this->config()->integration_type) {
case self::TYPE_ASSERT:
return 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient';
break;
case self::TYPE_LOGIN:
default:
return 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent';
break;
}
}
/**
* @param string $cfgName The static configuration value to get. This should be an array
* @param string $env The environment to return the value for. Must be one of the RealMe environment names
* @param string $integrationType The integration type (login or assert), if necessary, to determine return var
* @throws InvalidArgumentException If the cfgVar doesn't exist, or is malformed
* @return string|null Returns the value as defined in $cfgName for the given environment, or null if none exist
*/