forked from simplesamlphp/simplesamlphp-module-adfs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathADFS.php
More file actions
1043 lines (891 loc) · 38.9 KB
/
ADFS.php
File metadata and controls
1043 lines (891 loc) · 38.9 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
declare(strict_types=1);
namespace SimpleSAML\Module\adfs\IdP;
use DateInterval;
use DateTimeImmutable;
use DateTimeZone;
use Exception;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Configuration;
use SimpleSAML\Error;
use SimpleSAML\IdP;
use SimpleSAML\Logger;
use SimpleSAML\Metadata\MetaDataStorageHandler;
use SimpleSAML\Module;
use SimpleSAML\SAML11\Constants as C;
use SimpleSAML\SAML11\XML\saml\Assertion;
use SimpleSAML\SAML11\XML\saml\Attribute;
use SimpleSAML\SAML11\XML\saml\AttributeStatement;
use SimpleSAML\SAML11\XML\saml\AttributeValue;
use SimpleSAML\SAML11\XML\saml\Audience;
use SimpleSAML\SAML11\XML\saml\AudienceRestrictionCondition;
use SimpleSAML\SAML11\XML\saml\AuthenticationStatement;
use SimpleSAML\SAML11\XML\saml\Conditions;
use SimpleSAML\SAML11\XML\saml\ConfirmationMethod;
use SimpleSAML\SAML11\XML\saml\NameIdentifier;
use SimpleSAML\SAML11\XML\saml\Subject;
use SimpleSAML\SAML11\XML\saml\SubjectConfirmation;
use SimpleSAML\SAML2\Constants as SAML2_C;
use SimpleSAML\SOAP\Constants as SOAP_C;
use SimpleSAML\SOAP\XML\env_200305\Body;
use SimpleSAML\SOAP\XML\env_200305\Envelope;
use SimpleSAML\SOAP\XML\env_200305\Header;
use SimpleSAML\Utils;
use SimpleSAML\WSSecurity\XML\wsa_200508\Action;
use SimpleSAML\WSSecurity\XML\wsa_200508\Address;
use SimpleSAML\WSSecurity\XML\wsa_200508\EndpointReference;
use SimpleSAML\WSSecurity\XML\wsa_200508\MessageID;
use SimpleSAML\WSSecurity\XML\wsa_200508\RelatesTo;
use SimpleSAML\WSSecurity\XML\wsa_200508\To;
use SimpleSAML\WSSecurity\XML\wsp\AppliesTo;
use SimpleSAML\WSSecurity\XML\wsse\KeyIdentifier;
use SimpleSAML\WSSecurity\XML\wsse\Password;
use SimpleSAML\WSSecurity\XML\wsse\BinarySecurityToken;
use SimpleSAML\WSSecurity\XML\wsse\Security;
use SimpleSAML\WSSecurity\XML\wsse\SecurityTokenReference;
use SimpleSAML\WSSecurity\XML\wsse\UsernameToken;
use SimpleSAML\WSSecurity\XML\wst_200502\KeyType;
use SimpleSAML\WSSecurity\XML\wst_200502\Lifetime;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestedAttachedReference;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestedSecurityToken;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestedUnattachedReference;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestSecurityToken;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestSecurityTokenResponse;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestType;
use SimpleSAML\WSSecurity\XML\wst_200502\RequestTypeEnum;
use SimpleSAML\WSSecurity\XML\wst_200502\TokenType;
use SimpleSAML\WSSecurity\XML\wsu\Created;
use SimpleSAML\WSSecurity\XML\wsu\Expires;
use SimpleSAML\WSSecurity\XML\wsu\Timestamp;
use SimpleSAML\XHTML\Template;
use SimpleSAML\XML\Attribute as XMLAttribute;
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
use SimpleSAML\XMLSecurity\Key\PrivateKey;
use SimpleSAML\XMLSecurity\Key\X509Certificate as PublicKey;
use SimpleSAML\XMLSecurity\XML\ds\KeyInfo;
use SimpleSAML\XMLSecurity\XML\ds\Signature;
use SimpleSAML\XMLSecurity\XML\ds\X509Certificate;
use SimpleSAML\XMLSecurity\XML\ds\X509Data;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
use function array_pop;
use function base64_encode;
use function chunk_split;
use function str_replace;
use function trim;
class ADFS
{
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \SimpleSAML\SOAP\XML\env_200305\Envelope $soapEnvelope
* @param \SimpleSAML\Module\adfs\IdP\PassiveIdP $idp
* @throws \SimpleSAML\Error\MetadataNotFound
*/
public static function receivePassiveAuthnRequest(
Request $request,
Envelope $soapEnvelope,
PassiveIdP $idp,
): StreamedResponse {
// Parse the SOAP-header
$header = $soapEnvelope->getHeader();
$to = To::getChildrenOfClass($header->toXML());
Assert::count($to, 1, 'Missing To in SOAP Header.');
$to = array_pop($to);
$action = Action::getChildrenOfClass($header->toXML());
Assert::count($action, 1, 'Missing Action in SOAP Header.');
$action = array_pop($action);
$messageid = MessageID::getChildrenOfClass($header->toXML());
Assert::count($messageid, 1, 'Missing MessageID in SOAP Header.');
$messageid = array_pop($messageid);
$security = Security::getChildrenOfClass($header->toXML());
Assert::count($security, 1, 'Missing Security in SOAP Header.');
$security = array_pop($security);
// Parse the SOAP-body
$body = $soapEnvelope->getBody();
$requestSecurityToken = RequestSecurityToken::getChildrenOfClass($body->toXML());
Assert::count($requestSecurityToken, 1, 'Missing RequestSecurityToken in SOAP Body.');
$requestSecurityToken = array_pop($requestSecurityToken);
$appliesTo = AppliesTo::getChildrenOfClass($requestSecurityToken->toXML());
Assert::count($appliesTo, 1, 'Missing AppliesTo in RequestSecurityToken.');
$appliesTo = array_pop($appliesTo);
$endpointReference = EndpointReference::getChildrenOfClass($appliesTo->toXML());
Assert::count($endpointReference, 1, 'Missing EndpointReference in AppliesTo.');
$endpointReference = array_pop($endpointReference);
// Make sure the message was addressed to us.
if ($to === null || $request->server->get('SCRIPT_URI') !== $to->getContent()) {
throw new Error\BadRequest('This server is not the audience for the message received.');
}
// Ensure we know the issuer
$issuer = $endpointReference->getAddress()->getContent();
$metadata = MetaDataStorageHandler::getMetadataHandler(Configuration::getInstance());
$spMetadata = $metadata->getMetaDataConfig($issuer, 'adfs-sp-remote');
$usernameToken = UsernameToken::getChildrenOfClass($security->toXML());
Assert::count($usernameToken, 1, 'Missing UsernameToken in Security.');
$usernameToken = array_pop($usernameToken);
$username = $usernameToken->getUsername();
$password = Password::getChildrenOfClass($usernameToken->toXML());
$password = array_pop($password);
if ($password === null) {
throw new Error\BadRequest('Missing username or password in SOAP header.');
} else {
$_SERVER['PHP_AUTH_USER'] = $username->getContent();
$_SERVER['PHP_AUTH_PW'] = $password->getContent();
}
$requestSecurityTokenStr = $requestSecurityToken->toXML()->ownerDocument->saveXML();
$requestSecurityTokenStr = str_replace($password->getContent(), '*****', $requestSecurityTokenStr);
Logger::debug($requestSecurityTokenStr);
$state = [
'Responder' => [ADFS::class, 'sendPassiveResponse'],
'SPMetadata' => $spMetadata->toArray(),
'MessageID' => $messageid->getContent(),
// Dirty hack to leverage the SAML ECP logics
'saml:Binding' => SAML2_C::BINDING_PAOS,
];
return new StreamedResponse(
function () use ($idp, &$state) {
$idp->handleAuthenticationRequest($state);
},
);
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \SimpleSAML\SOAP\XML\env_200305\Envelope $soapEnvelope
* @param \SimpleSAML\Module\adfs\IdP\PassiveIdP $idp
* @return \Symfony\Component\HttpFoundation\StreamedResponse
* @throws \SimpleSAML\Error\MetadataNotFound
*/
public static function receiveCertificateAuthnRequest(
Request $request,
Envelope $soapEnvelope,
PassiveIdP $idp,
): StreamedResponse {
// Parse the SOAP-header
$header = $soapEnvelope->getHeader();
$to = To::getChildrenOfClass($header->toXML());
Assert::count($to, 1, 'Missing To in SOAP Header.');
$to = array_pop($to);
$action = Action::getChildrenOfClass($header->toXML());
Assert::count($action, 1, 'Missing Action in SOAP Header.');
$action = array_pop($action);
$messageid = MessageID::getChildrenOfClass($header->toXML());
Assert::count($messageid, 1, 'Missing MessageID in SOAP Header.');
$messageid = array_pop($messageid);
$security = Security::getChildrenOfClass($header->toXML());
Assert::count($security, 1, 'Missing Security in SOAP Header.');
$security = array_pop($security);
// Parse the SOAP-body
$body = $soapEnvelope->getBody();
$requestSecurityToken = RequestSecurityToken::getChildrenOfClass($body->toXML());
Assert::count($requestSecurityToken, 1, 'Missing RequestSecurityToken in SOAP Body.');
$requestSecurityToken = array_pop($requestSecurityToken);
$appliesTo = AppliesTo::getChildrenOfClass($requestSecurityToken->toXML());
Assert::count($appliesTo, 1, 'Missing AppliesTo in RequestSecurityToken.');
$appliesTo = array_pop($appliesTo);
$endpointReference = EndpointReference::getChildrenOfClass($appliesTo->toXML());
Assert::count($endpointReference, 1, 'Missing EndpointReference in AppliesTo.');
$endpointReference = array_pop($endpointReference);
// Make sure the message was addressed to us.
if ($to === null || $request->server->get('SCRIPT_URI') !== $to->getContent()) {
throw new Error\BadRequest('This server is not the audience for the message received.');
}
// Ensure we know the issuer
$issuer = $endpointReference->getAddress()->getContent();
$metadata = MetaDataStorageHandler::getMetadataHandler(Configuration::getInstance());
$spMetadata = $metadata->getMetaDataConfig($issuer, 'adfs-sp-remote');
// Extract Client Certificate
$bst = BinarySecurityToken::getChildrenOfClass($security->toXML());
Assert::count($bst, 1, 'Missing BinarySecurityToken in Security.');
$bst = array_pop($bst);
$clientCertData = $bst->getContent();
$clientCert = new PublicKey(PublicKey::normalizeCertificate($clientCertData));
// Verify XML Signature
$signatures = Signature::getChildrenOfClass($security->toXML());
Assert::count($signatures, 1, 'Missing Signature in Security header.');
/** @var \SimpleSAML\XMLSecurity\XML\ds\Signature $signature */
$signature = array_pop($signatures);
// Verify the signature against the client certificate
if (!$signature->verify($clientCert)) {
throw new Error\BadRequest('SOAP Signature verification failed.');
}
// Verify Certificate Chain against Trusted CAs
$idpConfig = $idp->getConfig();
$caFiles = $idpConfig->getOptionalArray('certificate_authorities', []);
if (empty($caFiles)) {
throw new Error\Exception('No certificate authorities configured for ADFS certificatemixed endpoint.');
}
// Create a temporary file to hold the client cert for openssl check
$clientCertPem = $clientCert->getPEM();
$verified = false;
foreach ($caFiles as $caFile) {
// Resolve path
$configUtils = new Utils\Config();
$caFilePath = $configUtils->getCertPath($caFile);
// Verify
$certRes = openssl_x509_read($clientCertPem);
if ($certRes) {
$result = openssl_x509_checkpurpose($certRes, X509_PURPOSE_SSL_CLIENT, [$caFilePath]);
if ($result === true) {
$verified = true;
break;
}
}
}
if (!$verified) {
throw new Error\BadRequest('Client certificate could not be verified against trusted CAs.');
}
// Authenticate User
$certDetails = openssl_x509_parse($clientCertPem);
$subject = $certDetails['subject'];
$subjectDN = ''; // Reconstruct DN or use what's available
// openssl_x509_parse returns subject as array.
// We can just use the name from the parser or try to get the DN string.
// Simple mapping: Use the CN or emailAddress from Subject
$username = null;
if (isset($subject['emailAddress'])) {
$username = $subject['emailAddress'];
} elseif (isset($subject['CN'])) {
$username = $subject['CN'];
}
// Also check SANs
if (isset($certDetails['extensions']['subjectAltName'])) {
// Format usually: "email:foo@bar.com, DNS:example.com"
$sans = explode(',', $certDetails['extensions']['subjectAltName']);
foreach ($sans as $san) {
$san = trim($san);
if (str_starts_with($san, 'email:')) {
$username = substr($san, 6);
break;
}
if (str_starts_with($san, 'othername:') && strpos($san, '1.3.6.1.4.1.311.20.2.3') !== false) {
// UPN OID
// Parsing UPN from othername is complex (ASN.1). Skipping for simplicity unless needed.
}
}
}
if (!$username) {
throw new Error\BadRequest('Could not extract username (CN, Email, or SAN Email) from client certificate.');
}
Logger::info('ADFS certificatemixed: Authenticated user ' . $username);
$attributes = [
'http://schemas.xmlsoap.org/claims/UPN' => [$username],
'http://schemas.microsoft.com/LiveID/Federation/2008/05/ImmutableID' => [$username], // Fallback
// Add other attributes if available or mapped
];
$state = [
'Responder' => [ADFS::class, 'sendPassiveResponse'],
'SPMetadata' => $spMetadata->toArray(),
'MessageID' => $messageid->getContent(),
'saml:Binding' => SAML2_C::BINDING_PAOS,
'Attributes' => $attributes,
'IdPMetadata' => $idpConfig->toArray(),
'saml:NameID' => [SAML2_C::NAMEID_UNSPECIFIED => new \SimpleSAML\SAML2\XML\saml\NameID($username)],
'adfs:wctx' => null, // Not usually present in this flow or extracted differently?
// In receivePassiveAuthnRequest (usernamemixed), wctx is not extracted from query,
// but the SOAP request might contain context?
// Standard usernamemixed flow doesn't use wctx in the SOAP body usually.
'adfs:wreply' => $spMetadata->getValue('prp'),
];
// Call sendPassiveResponse directly
return new StreamedResponse(
function () use ($state) {
ADFS::sendPassiveResponse($state);
},
);
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @param \SimpleSAML\IdP $idp
* @throws \SimpleSAML\Error\MetadataNotFound
*/
public static function receiveAuthnRequest(Request $request, IdP $idp): StreamedResponse
{
parse_str($request->server->get('QUERY_STRING'), $query);
$requestid = $query['wctx'] ?? null;
$issuer = $query['wtrealm'];
$metadata = MetaDataStorageHandler::getMetadataHandler(Configuration::getInstance());
$spMetadata = $metadata->getMetaDataConfig($issuer, 'adfs-sp-remote');
Logger::info('ADFS - IdP.prp: Incoming Authentication request: ' . $issuer . ' id ' . $requestid);
$username = null;
if ($request->query->has('username')) {
$username = (string) $request->query->get('username');
}
$wauth = null;
if ($request->query->has('wauth')) {
$wauth = (string) $request->query->get('wauth');
}
$state = [
'Responder' => [ADFS::class, 'sendResponse'],
'SPMetadata' => $spMetadata->toArray(),
'ForceAuthn' => false,
'isPassive' => false,
'adfs:wctx' => $requestid,
'adfs:wreply' => false,
];
if ($username !== null) {
$state['core:username'] = $username;
}
if ($wauth !== null) {
$state['saml:RequestedAuthnContext'] = ['AuthnContextClassRef' => [$wauth]];
}
if (isset($query['wreply']) && !empty($query['wreply'])) {
$httpUtils = new Utils\HTTP();
$state['adfs:wreply'] = $httpUtils->checkURLAllowed($query['wreply']);
}
return new StreamedResponse(
function () use ($idp, &$state) {
$idp->handleAuthenticationRequest($state);
},
);
}
/**
* @param string $issuer
* @param string $target
* @param string $nameid
* @param array<mixed> $attributes
* @param int $assertionLifetime
* @param string $method
* @return \SimpleSAML\SAML11\XML\saml\Assertion
*/
private static function generateActiveAssertion(
string $issuer,
string $target,
string $nameid,
array $attributes,
int $assertionLifetime,
string $method,
): Assertion {
$httpUtils = new Utils\HTTP();
$randomUtils = new Utils\Random();
$timeUtils = new Utils\Time();
$issueInstant = $timeUtils->generateTimestamp();
$notBefore = DateInterval::createFromDateString('30 seconds');
$notOnOrAfter = DateInterval::createFromDateString(sprintf('%d seconds', $assertionLifetime));
$assertionID = $randomUtils->generateID();
$nameidFormat = 'http://schemas.xmlsoap.org/claims/UPN';
$nameid = htmlspecialchars($nameid);
$now = new DateTimeImmutable('now', new DateTimeZone('Z'));
$audience = new Audience($target);
$audienceRestrictionCondition = new AudienceRestrictionCondition([$audience]);
$conditions = new Conditions(
[$audienceRestrictionCondition],
[],
[],
$now->sub($notBefore),
$now->add($notOnOrAfter),
);
$nameIdentifier = new NameIdentifier($nameid, null, $nameidFormat);
$subject = new Subject(null, $nameIdentifier);
$authenticationStatement = new AuthenticationStatement($subject, $method, $now);
$attrs = [];
$attrUtils = new Utils\Attributes();
foreach ($attributes as $name => $values) {
if ((!is_array($values)) || (count($values) == 0)) {
continue;
}
list($namespace, $name) = $attrUtils->getAttributeNamespace(
$name,
'http://schemas.xmlsoap.org/claims',
);
$namespace = htmlspecialchars($namespace);
$name = htmlspecialchars($name);
$attrValue = [];
foreach ($values as $value) {
if ((!isset($value)) || ($value === '')) {
continue;
}
$attrValue[] = new AttributeValue($value);
}
$attrs[] = new Attribute($name, $namespace, $attrValue);
}
$attributeStatement = new AttributeStatement($subject, $attrs);
return new Assertion(
$assertionID,
$issuer,
$now,
$conditions,
null, // Advice
[$authenticationStatement, $attributeStatement],
);
}
/**
* @param string $issuer
* @param string $target
* @param string $nameid
* @param array<mixed> $attributes
* @param int $assertionLifetime
* @return \SimpleSAML\SAML11\XML\saml\Assertion
*/
private static function generatePassiveAssertion(
string $issuer,
string $target,
string $nameid,
array $attributes,
int $assertionLifetime,
): Assertion {
$httpUtils = new Utils\HTTP();
$randomUtils = new Utils\Random();
$timeUtils = new Utils\Time();
$issueInstant = $timeUtils->generateTimestamp();
$notBefore = DateInterval::createFromDateString('30 seconds');
$notOnOrAfter = DateInterval::createFromDateString(sprintf('%d seconds', $assertionLifetime));
$assertionID = $randomUtils->generateID();
$now = new DateTimeImmutable('now', new DateTimeZone('Z'));
if ($httpUtils->isHTTPS()) {
$method = SAML2_C::AC_PASSWORD_PROTECTED_TRANSPORT;
} else {
$method = C::AC_PASSWORD;
}
$audience = new Audience($target);
$audienceRestrictionCondition = new AudienceRestrictionCondition([$audience]);
$conditions = new Conditions(
[$audienceRestrictionCondition],
[],
[],
$now->sub($notBefore),
$now->add($notOnOrAfter),
);
$nameIdentifier = new NameIdentifier($nameid, null, C::NAMEID_UNSPECIFIED);
$subject = new Subject(new SubjectConfirmation([new ConfirmationMethod(C::CM_BEARER)]), $nameIdentifier);
$authenticationStatement = new AuthenticationStatement($subject, $method, $now);
$attrs = [];
$attrs[] = new Attribute(
'UPN',
'http://schemas.xmlsoap.org/claims',
[new AttributeValue($attributes['http://schemas.xmlsoap.org/claims/UPN'][0])],
);
$attrs[] = new Attribute(
'ImmutableID',
'http://schemas.microsoft.com/LiveID/Federation/2008/05',
[new AttributeValue($attributes['http://schemas.microsoft.com/LiveID/Federation/2008/05/ImmutableID'][0])],
);
$attributeStatement = new AttributeStatement($subject, $attrs);
return new Assertion(
$assertionID,
$issuer,
$now,
$conditions,
null, // Advice
[$attributeStatement, $authenticationStatement],
);
}
/**
* @param \SimpleSAML\SAML11\XML\saml\Assertion $assertion
* @param string $key
* @param string $cert
* @param string $algo
* @param string|null $passphrase
* @return \SimpleSAML\SAML11\XML\saml\Assertion
*/
private static function signAssertion(
Assertion $assertion,
string $key,
string $cert,
string $algo,
#[\SensitiveParameter]
?string $passphrase = null,
): Assertion {
$key = PrivateKey::fromFile($key, $passphrase);
$pubkey = PublicKey::fromFile($cert);
$keyInfo = new KeyInfo([
new X509Data(
[new X509Certificate(
trim(chunk_split(base64_encode($pubkey->getPEM()->data()))),
)],
),
]);
$signer = (new SignatureAlgorithmFactory())->getAlgorithm(
$algo,
$key,
);
$assertion->sign($signer, C::C14N_EXCLUSIVE_WITHOUT_COMMENTS, $keyInfo);
return $assertion;
}
/**
* @param string $wreply
* @param string $wresult
* @param ?string $wctx
*/
private static function postResponse(string $wreply, string $wresult, ?string $wctx): void
{
$config = Configuration::getInstance();
$t = new Template($config, 'adfs:postResponse.twig');
$t->data['wreply'] = $wreply;
$t->data['wresult'] = $wresult;
$t->data['wctx'] = $wctx;
$t->send();
// Idp->postAuthProc expects this function to exit
exit();
}
/**
* Get the metadata of a given hosted ADFS IdP.
*
* @param string $entityid The entity ID of the hosted ADFS IdP whose metadata we want to fetch.
* @param \SimpleSAML\Metadata\MetaDataStorageHandler $handler Optionally the metadata storage to use,
* if omitted the configured handler will be used.
* @return array
*
* @throws \SimpleSAML\Error\Exception
* @throws \SimpleSAML\Error\MetadataNotFound
*/
public static function getHostedMetadata(string $entityid, ?MetaDataStorageHandler $handler = null): array
{
$cryptoUtils = new Utils\Crypto();
$globalConfig = Configuration::getInstance();
if ($handler === null) {
$handler = MetaDataStorageHandler::getMetadataHandler($globalConfig);
}
$config = $handler->getMetaDataConfig($entityid, 'adfs-idp-hosted');
$host = Module::getModuleURL('adfs/idp/prp.php');
// configure endpoints
$ssob = $handler->getGenerated('SingleSignOnServiceBinding', 'adfs-idp-hosted', $host);
$slob = $handler->getGenerated('SingleLogoutServiceBinding', 'adfs-idp-hosted', $host);
$ssol = $handler->getGenerated('SingleSignOnService', 'adfs-idp-hosted', $host);
$slol = $handler->getGenerated('SingleLogoutService', 'adfs-idp-hosted', $host);
$sso = [];
if (is_array($ssob)) {
foreach ($ssob as $binding) {
$sso[] = [
'Binding' => $binding,
'Location' => $ssol,
];
}
} else {
$sso[] = [
'Binding' => $ssob,
'Location' => $ssol,
];
}
$slo = [];
if (is_array($slob)) {
foreach ($slob as $binding) {
$slo[] = [
'Binding' => $binding,
'Location' => $slol,
];
}
} else {
$slo[] = [
'Binding' => $slob,
'Location' => $slol,
];
}
$metadata = [
'metadata-set' => 'adfs-idp-hosted',
'entityid' => $entityid,
'SingleSignOnService' => $sso,
'SingleLogoutService' => $slo,
'NameIDFormat' => $config->getOptionalArrayizeString('NameIDFormat', [C::NAMEID_TRANSIENT]),
'contacts' => [],
];
// add certificates
$keys = [];
$certInfo = $cryptoUtils->loadPublicKey($config, false, 'new_');
$hasNewCert = false;
if ($certInfo !== null) {
$keys[] = [
'type' => 'X509Certificate',
'signing' => true,
'encryption' => true,
'X509Certificate' => $certInfo['certData'],
'prefix' => 'new_',
];
$hasNewCert = true;
}
/** @var array $certInfo */
$certInfo = $cryptoUtils->loadPublicKey($config, true);
$keys[] = [
'type' => 'X509Certificate',
'signing' => true,
'encryption' => $hasNewCert === false,
'X509Certificate' => $certInfo['certData'],
'prefix' => '',
];
if ($config->hasValue('https.certificate')) {
/** @var array $httpsCert */
$httpsCert = $cryptoUtils->loadPublicKey($config, true, 'https.');
$keys[] = [
'type' => 'X509Certificate',
'signing' => true,
'encryption' => false,
'X509Certificate' => $httpsCert['certData'],
'prefix' => 'https.',
];
}
$metadata['keys'] = $keys;
// add organization information
if ($config->hasValue('OrganizationName')) {
$metadata['OrganizationName'] = $config->getLocalizedString('OrganizationName');
$metadata['OrganizationDisplayName'] = $config->getOptionalLocalizedString(
'OrganizationDisplayName',
$metadata['OrganizationName'],
);
if (!$config->hasValue('OrganizationURL')) {
throw new Error\Exception('If OrganizationName is set, OrganizationURL must also be set.');
}
$metadata['OrganizationURL'] = $config->getLocalizedString('OrganizationURL');
}
// add scope
if ($config->hasValue('scope')) {
$metadata['scope'] = $config->getArray('scope');
}
// add extensions
if ($config->hasValue('EntityAttributes')) {
$metadata['EntityAttributes'] = $config->getArray('EntityAttributes');
// check for entity categories
if (Utils\Config\Metadata::isHiddenFromDiscovery($metadata)) {
$metadata['hide.from.discovery'] = true;
}
}
if ($config->hasValue('UIInfo')) {
$metadata['UIInfo'] = $config->getArray('UIInfo');
}
if ($config->hasValue('DiscoHints')) {
$metadata['DiscoHints'] = $config->getArray('DiscoHints');
}
if ($config->hasValue('RegistrationInfo')) {
$metadata['RegistrationInfo'] = $config->getArray('RegistrationInfo');
}
// add contact information
$globalConfig = Configuration::getInstance();
$email = $globalConfig->getOptionalString('technicalcontact_email', null);
if ($email !== null && $email !== 'na@example.org') {
$contact = [
'emailAddress' => $email,
'givenName' => $globalConfig->getOptionalString('technicalcontact_name', null),
'contactType' => 'technical',
];
$metadata['contacts'][] = Utils\Config\Metadata::getContact($contact);
}
return $metadata;
}
/**
* @param array<mixed> $state
* @throws \Exception
*/
public static function sendPassiveResponse(array $state): void
{
$idp = IdP::getByState($state);
$idpMetadata = $idp->getConfig();
$idpEntityId = $state['IdPMetadata']['entityid'];
$spMetadata = $state['SPMetadata'];
$spEntityId = $spMetadata['entityid'];
$spMetadata = Configuration::loadFromArray(
$spMetadata,
'$metadata[' . var_export($spEntityId, true) . ']',
);
$assertionLifetime = $spMetadata->getOptionalInteger('assertion.lifetime', null);
if ($assertionLifetime === null) {
$assertionLifetime = $idpMetadata->getOptionalInteger('assertion.lifetime', 300);
}
$now = new DateTimeImmutable('now', new DateTimeZone('Z'));
$created = $now->sub(DateInterval::createFromDateString(sprintf('30 seconds')));
$expires = $now->add(DateInterval::createFromDateString(sprintf('%d seconds', $assertionLifetime)));
$attributes = $state['Attributes'];
$nameid = $state['saml:NameID'][SAML2_C::NAMEID_UNSPECIFIED];
$assertion = ADFS::generatePassiveAssertion(
$idpEntityId,
$spEntityId,
$nameid->getValue(),
$attributes,
$assertionLifetime,
);
$privateKeyCfg = $idpMetadata->getOptionalString('privatekey', null);
$certificateCfg = $idpMetadata->getOptionalString('certificate', null);
if ($privateKeyCfg !== null && $certificateCfg !== null) {
$configUtils = new Utils\Config();
$privateKeyFile = $configUtils->getCertPath($privateKeyCfg);
$certificateFile = $configUtils->getCertPath($certificateCfg);
$passphrase = $idpMetadata->getOptionalString('privatekey_pass', null);
$algo = $spMetadata->getOptionalString('signature.algorithm', null);
if ($algo === null) {
$algo = $idpMetadata->getOptionalString('signature.algorithm', C::SIG_RSA_SHA256);
}
$assertion = ADFS::signAssertion($assertion, $privateKeyFile, $certificateFile, $algo, $passphrase);
$assertion = Assertion::fromXML($assertion->toXML());
}
$requestedSecurityToken = new RequestedSecurityToken($assertion);
$lifetime = new LifeTime(new Created($created), new Expires($expires));
$appliesTo = new AppliesTo([new EndpointReference(new Address($spEntityId))]);
$requestedAttachedReference = new RequestedAttachedReference(
new SecurityTokenReference(null, null, [
new KeyIdentifier(
$assertion->getId(),
'http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID',
),
]),
);
$requestedUnattachedReference = new RequestedUnattachedReference(
new SecurityTokenReference(null, null, [
new KeyIdentifier(
$assertion->getId(),
'http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID',
),
]),
);
$tokenType = new TokenType(C::NS_SAML);
$requestType = new RequestType([RequestTypeEnum::Issue]);
$keyType = new KeyType(['http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey']);
$requestSecurityTokenResponse = new RequestSecurityTokenResponse(null, [
$lifetime,
$appliesTo,
$requestedSecurityToken,
$requestedAttachedReference,
$requestedUnattachedReference,
$tokenType,
$requestType,
$keyType,
]);
// Build envelope
$mustUnderstand = new XMLAttribute(SOAP_C::NS_SOAP_ENV_12, 'env', 'mustUnderstand', '1');
$header = new Header([
new Action('http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue', [$mustUnderstand]),
new RelatesTo($state['MessageID'], null),
new Security(
[
new Timestamp(
new Created($created),
new Expires($expires),
),
],
[$mustUnderstand],
),
]);
$body = new Body(null, [$requestSecurityTokenResponse]);
$envelope = new Envelope($body, $header);
$xmlResponse = $envelope->toXML();
\SimpleSAML\Logger::debug($xmlResponse->ownerDocument->saveXML($xmlResponse));
echo $xmlResponse->ownerDocument->saveXML($xmlResponse);
exit();
}
/**
* @param array<mixed> $state
* @throws \Exception
*/
public static function sendResponse(array $state): void
{
$spMetadata = $state['SPMetadata'];
$spEntityId = $spMetadata['entityid'];
$spMetadata = Configuration::loadFromArray(
$spMetadata,
'$metadata[' . var_export($spEntityId, true) . ']',
);
$attributes = $state['Attributes'];
$nameidattribute = $spMetadata->getValue('simplesaml.nameidattribute');
if (!empty($nameidattribute)) {
if (!array_key_exists($nameidattribute, $attributes)) {
throw new Exception('simplesaml.nameidattribute does not exist in resulting attribute set');
}
$nameid = $attributes[$nameidattribute][0];
} else {
$randomUtils = new Utils\Random();
$nameid = $randomUtils->generateID();
}
$idp = IdP::getByState($state);
$idpMetadata = $idp->getConfig();
$idpEntityId = $state['IdPMetadata']['entityid'];
$idp->addAssociation([
'id' => 'adfs:' . $spEntityId,
'Handler' => ADFS::class,
'adfs:entityID' => $spEntityId,
]);
$assertionLifetime = $spMetadata->getOptionalInteger('assertion.lifetime', null);
if ($assertionLifetime === null) {
$assertionLifetime = $idpMetadata->getOptionalInteger('assertion.lifetime', 300);
}
if (isset($state['saml:AuthnContextClassRef'])) {
$method = $state['saml:AuthnContextClassRef'];
} elseif ((new Utils\HTTP())->isHTTPS()) {
$method = SAML2_C::AC_PASSWORD_PROTECTED_TRANSPORT;
} else {
$method = C::AC_PASSWORD;
}
$assertion = ADFS::generateActiveAssertion(
$idpEntityId,
$spEntityId,
$nameid,
$attributes,
$assertionLifetime,
$method,
);
$privateKeyCfg = $idpMetadata->getOptionalString('privatekey', null);
$certificateCfg = $idpMetadata->getOptionalString('certificate', null);
if ($privateKeyCfg !== null && $certificateCfg !== null) {
$configUtils = new Utils\Config();
$privateKeyFile = $configUtils->getCertPath($privateKeyCfg);
$certificateFile = $configUtils->getCertPath($certificateCfg);
$passphrase = $idpMetadata->getOptionalString('privatekey_pass', null);
$algo = $spMetadata->getOptionalString('signature.algorithm', null);
if ($algo === null) {
$algo = $idpMetadata->getOptionalString('signature.algorithm', C::SIG_RSA_SHA256);
}
$assertion = ADFS::signAssertion($assertion, $privateKeyFile, $certificateFile, $algo, $passphrase);
$assertion = Assertion::fromXML($assertion->toXML());
}
$requestedSecurityToken = new RequestedSecurityToken($assertion);
$appliesTo = new AppliesTo([new EndpointReference(new Address($spEntityId))]);
$requestSecurityTokenResponse = new RequestSecurityTokenResponse(null, [$requestedSecurityToken, $appliesTo]);
$xmlResponse = $requestSecurityTokenResponse->toXML();
$wresult = $xmlResponse->ownerDocument->saveXML($xmlResponse);
Logger::debug($wresult);
$wctx = $state['adfs:wctx'];
$wreply = $state['adfs:wreply'] ? : $spMetadata->getValue('prp');
ADFS::postResponse($wreply, $wresult, $wctx);
}
/**
* @param \SimpleSAML\IdP $idp
* @param array<mixed> $state
*/
public static function sendLogoutResponse(IdP $idp, array $state): void
{
// NB:: we don't know from which SP the logout request came from
$idpMetadata = $idp->getConfig();
$httpUtils = new Utils\HTTP();
$httpUtils->redirectTrustedURL(
$idpMetadata->getOptionalString('redirect-after-logout', $httpUtils->getBaseURL()),
);
}
/**
* @param \SimpleSAML\IdP $idp
* @throws \Exception
*/
public static function receiveLogoutMessage(IdP $idp): void