forked from simplesamlphp/simplesamlphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSAMLParser.php
More file actions
1250 lines (1056 loc) · 45.1 KB
/
SAMLParser.php
File metadata and controls
1250 lines (1056 loc) · 45.1 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\Metadata;
use DOMDocument;
use DOMElement;
use Exception;
use RobRichards\XMLSecLibs\XMLSecurityKey;
use SAML2\XML\md\EntitiesDescriptor;
use SAML2\XML\md\EntityDescriptor;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Logger;
use SimpleSAML\SAML2\Constants as C;
use SimpleSAML\SAML2\XML\idpdisc\DiscoveryResponse;
use SimpleSAML\SAML2\XML\md\AbstractEndpointType;
use SimpleSAML\SAML2\XML\md\AttributeAuthorityDescriptor;
use SimpleSAML\SAML2\XML\md\AttributeConsumingService;
use SimpleSAML\SAML2\XML\md\ContactPerson;
use SimpleSAML\SAML2\XML\md\IDPSSODescriptor;
use SimpleSAML\SAML2\XML\md\KeyDescriptor;
use SimpleSAML\SAML2\XML\md\SPSSODescriptor;
use SimpleSAML\SAML2\XML\md\SSODescriptorType;
use SimpleSAML\SAML2\XML\mdattr\EntityAttributes;
use SimpleSAML\SAML2\XML\mdrpi\RegistrationInfo;
use SimpleSAML\SAML2\XML\mdui\DiscoHints;
use SimpleSAML\SAML2\XML\mdui\UIInfo;
use SimpleSAML\SAML2\XML\saml\Attribute;
use SimpleSAML\SAML2\XML\shibmd\Scope;
use SimpleSAML\Utils;
use SimpleSAML\XML\DOMDocumentFactory;
use SimpleSAML\XMLSecurity\XML\ds\X509Certificate;
use SimpleSAML\XMLSecurity\XML\ds\X509Data;
use Symfony\Component\Filesystem\Filesystem;
use function array_diff;
use function array_intersect;
use function array_key_exists;
use function array_map;
use function array_merge;
use function count;
use function sprintf;
/**
* This is class for parsing of SAML 2.0 metadata.
*
* Metadata is loaded by calling the static methods parseFile, parseString or parseElement.
* These functions returns an instance of SAMLParser. To get metadata
* from this object, use the method getMetadata20SP.
*
* To parse a file which can contain a collection of EntityDescriptor or EntitiesDescriptor elements, use the
* parseDescriptorsFile, parseDescriptorsString or parseDescriptorsElement methods. These functions will return
* an array of SAMLParser elements where each element represents an EntityDescriptor-element.
*/
class SAMLParser
{
/**
* This is the list with the SAML 2.0 protocol.
*
* @var string[]
*/
private static array $SAML20Protocols = [
C::NS_SAMLP,
];
/**
* This is the entity id we find in the metadata.
*
* @var string
*/
private string $entityId;
/**
* This is an array with the processed SPSSODescriptor elements we have found in this
* metadata file.
* Each element in the array is an associative array with the elements from parseSSODescriptor and:
* - 'AssertionConsumerService': Array with the SP's assertion consumer services.
* Each assertion consumer service is stored as an associative array with the
* elements that parseGenericEndpoint returns.
*
* @var array
*/
private array $spDescriptors = [];
/**
* This is an array with the processed IDPSSODescriptor elements we have found.
* Each element in the array is an associative array with the elements from parseSSODescriptor and:
* - 'SingleSignOnService': Array with the IdP's single sign on service endpoints. Each endpoint is stored
* as an associative array with the elements that parseGenericEndpoint returns.
*
* @var array
*/
private array $idpDescriptors = [];
/**
* List of attribute authorities we have found.
*
* @var array
*/
private array $attributeAuthorityDescriptors = [];
/**
* This is an associative array with the organization name for this entity. The key of
* the associative array is the language code, while the value is a string with the
* organization name.
*
* @var array<string, string>
*/
private array $organizationName = [];
/**
* This is an associative array with the organization display name for this entity. The key of
* the associative array is the language code, while the value is a string with the
* organization display name.
*
* @var array<string, string>
*/
private array $organizationDisplayName = [];
/**
* This is an associative array with the organization URI for this entity. The key of
* the associative array is the language code, while the value is the URI.
*
* @var array<string, string>
*/
private array $organizationURL = [];
/**
* This is an array of the Contact Persons of this entity.
*
* @var array
*/
private array $contacts = [];
/**
* @var array
*/
private array $scopes;
/**
* @var array
*/
private array $entityAttributes;
/**
* An associative array of attributes from the RegistrationInfo element.
* @var array
*/
private array $registrationInfo;
/**
* This is an array of elements that may be used to validate this element.
*
* @var \SAML2\SignedElementHelper[]
*/
private array $validators = [];
/**
* @var \Symfony\Component\Filesystem\Filesystem
*/
protected Filesystem $fileSystem;
/**
* This is the constructor for the SAMLParser class.
*
* @param \SimpleSAML\SAML2\XML\md\EntityDescriptor $entityElement The EntityDescriptor.
* @param int|null $maxExpireTime The unix timestamp for when this entity should expire, or
* NULL if unknown.
* @param array $validators An array of parent elements that may validate this element.
* @param array $parentExtensions An optional array of extensions from the parent element.
* @throws \Exception
*/
private function __construct(
EntityDescriptor $entityElement,
?int $maxExpireTime,
array $validators = [],
array $parentExtensions = [],
) {
$this->fileSystem = new Filesystem();
$this->entityId = $entityElement->getEntityID();
$expireTime = self::getExpireTime($entityElement, $maxExpireTime);
$this->validators = $validators;
$this->validators[] = $entityElement;
// process Extensions element, if it exists
$ext = self::processExtensions($entityElement, $parentExtensions);
$this->scopes = $ext['scope'];
$this->entityAttributes = $ext['EntityAttributes'];
$this->registrationInfo = $ext['RegistrationInfo'];
// look over the RoleDescriptors
foreach ($entityElement->getRoleDescriptor() as $child) {
if ($child instanceof SPSSODescriptor) {
$this->processSPSSODescriptor($child, $expireTime);
} elseif ($child instanceof IDPSSODescriptor) {
$this->processIDPSSODescriptor($child, $expireTime);
} elseif ($child instanceof AttributeAuthorityDescriptor) {
$this->processAttributeAuthorityDescriptor($child, $expireTime);
}
}
$organization = $entityElement->getOrganization();
if ($organization !== null) {
$this->processOrganization($organization);
}
if ($entityElement->getContactPerson() !== []) {
foreach ($entityElement->getContactPerson() as $contact) {
$this->processContactPerson($contact);
}
}
}
/**
* This function parses a file which contains XML encoded metadata.
*
* @param string $file The path to the file which contains the metadata.
*
* @return \SimpleSAML\Metadata\SAMLParser An instance of this class with the metadata loaded.
* @throws \Exception If the file does not parse as XML.
*/
public static function parseFile(string $file): SAMLParser
{
$httpUtils = new Utils\HTTP();
/** @var string $data */
$data = $httpUtils->fetch($file);
try {
$doc = DOMDocumentFactory::fromString($data);
} catch (Exception $e) {
throw new Exception('Failed to read XML from file: ' . $file);
}
return self::parseDocument($doc);
}
/**
* This function parses a string which contains XML encoded metadata.
*
* @param string $metadata A string which contains XML encoded metadata.
*
* @return \SimpleSAML\Metadata\SAMLParser An instance of this class with the metadata loaded.
* @throws \Exception If the string does not parse as XML.
*/
public static function parseString(string $metadata): SAMLParser
{
try {
$doc = DOMDocumentFactory::fromString($metadata);
} catch (Exception $e) {
throw new Exception('Failed to parse XML string.');
}
return self::parseDocument($doc);
}
/**
* This function parses a \DOMDocument which is assumed to contain a single EntityDescriptor element.
*
* @param \DOMDocument $document The \DOMDocument which contains the EntityDescriptor element.
*
* @return \SimpleSAML\Metadata\SAMLParser An instance of this class with the metadata loaded.
* @throws \Exception
*/
public static function parseDocument(DOMDocument $document): SAMLParser
{
$entityElement = self::findEntityDescriptor($document);
return self::parseElement($entityElement);
}
/**
* This function parses a \SimpleSAML\SAML2\XML\md\EntityDescriptor object which represents
* a EntityDescriptor element.
*
* @param \SimpleSAML\SAML2\XML\md\EntityDescriptor $entityElement A \SimpleSAML\SAML2\XML\md\EntityDescriptor
* object which represents a EntityDescriptor element.
*
* @return \SimpleSAML\Metadata\SAMLParser An instance of this class with the metadata loaded.
* @throws \Exception
*/
public static function parseElement(EntityDescriptor $entityElement): SAMLParser
{
return new SAMLParser($entityElement, null, []);
}
/**
* This function parses a file where the root node is either an EntityDescriptor element or an
* EntitiesDescriptor element. In both cases it will return an associative array of SAMLParser instances. If
* the file contains a single EntityDescriptorElement, then the array will contain a single SAMLParser
* instance.
*
* @param string $file The path to the file which contains the EntityDescriptor or EntitiesDescriptor element.
* @param array $context The connection context to pass to file_get_contents()
*
* @return \SimpleSAML\Metadata\SAMLParser[] An array of SAMLParser instances.
* @throws \Exception If the file does not parse as XML.
*/
public static function parseDescriptorsFile(string $file, array $context = []): array
{
if (empty($file)) {
throw new Exception('Cannot open file; file name not specified.');
}
/** @var string $data */
$httpUtils = new Utils\HTTP();
$data = $httpUtils->fetch($file, $context);
try {
$doc = DOMDocumentFactory::fromString($data);
} catch (Exception $e) {
throw new Exception('Failed to read XML from file: ' . $file);
}
return self::parseDescriptorsElement($doc->documentElement);
}
/**
* This function parses a string with XML data. The root node of the XML data is expected to be either an
* EntityDescriptor element or an EntitiesDescriptor element. It will return an associative array of
* SAMLParser instances.
*
* @param string $string The string with XML data.
*
* @return \SimpleSAML\Metadata]SAMLParser[] An associative array of SAMLParser instances.
* The key of the array will be the entity id.
* @throws \Exception If the string does not parse as XML.
*/
public static function parseDescriptorsString(string $string): array
{
try {
$doc = DOMDocumentFactory::fromString($string);
} catch (Exception $e) {
throw new Exception('Failed to parse XML string.');
}
return self::parseDescriptorsElement($doc->documentElement);
}
/**
* This function parses a DOMElement which represents either an EntityDescriptor element or an
* EntitiesDescriptor element. It will return an associative array of SAMLParser instances in both cases.
*
* @param \DOMElement|null $element The DOMElement which contains the EntityDescriptor element or the
* EntitiesDescriptor element.
*
* @return \SimpleSAML\Metadata\SAMLParser[] An associative array of SAMLParser instances.
* The key of the array will be the entity id.
* @throws \Exception if the document is empty or the root is an unexpected node.
*/
public static function parseDescriptorsElement(?DOMElement $element = null): array
{
if ($element === null) {
throw new Exception('Document was empty.');
}
$xmlUtils = new Utils\XML();
if ($xmlUtils->isDOMNodeOfType($element, 'EntityDescriptor', '@md') === true) {
return self::processDescriptorsElement(new EntityDescriptor($element));
} elseif ($xmlUtils->isDOMNodeOfType($element, 'EntitiesDescriptor', '@md') === true) {
return self::processDescriptorsElement(new EntitiesDescriptor($element));
} else {
throw new Exception('Unexpected root node: [' . $element->namespaceURI . ']:' . $element->localName);
}
}
/**
*
* @param \SAML2\XML\md\EntityDescriptor|\SAML2\XML\md\EntitiesDescriptor $element The element we should process.
* @param int|null $maxExpireTime The maximum expiration time of the entities.
* @param array $validators The parent-elements that may be signed.
* @param array $parentExtensions An optional array of extensions from the parent element.
* @throws \Exception
*
* @return \SimpleSAML\Metadata\SAMLParser[] Array of SAMLParser instances.
*/
private static function processDescriptorsElement(
SignedElementHelper $element,
?int $maxExpireTime = null,
array $validators = [],
array $parentExtensions = [],
): array {
if ($element instanceof EntityDescriptor) {
$ret = new SAMLParser($element, $maxExpireTime, $validators, $parentExtensions);
$ret = [$ret->getEntityId() => $ret];
/** @var \SimpleSAML\Metadata\SAMLParser[] $ret */
return $ret;
}
Assert::isInstanceOf($element, EntitiesDescriptor::class);
$extensions = self::processExtensions($element, $parentExtensions);
$expTime = self::getExpireTime($element, $maxExpireTime);
$validators[] = $element;
$ret = [];
foreach ($element->getChildren() as $child) {
$ret += self::processDescriptorsElement($child, $expTime, $validators, $extensions);
}
return $ret;
}
/**
* Determine how long a given element can be cached.
*
* This function looks for the 'validUntil' attribute to determine
* how long a given XML-element is valid. It returns this as a unix timestamp.
*
* @param mixed $element The element we should determine the expiry time of.
* @param int|null $maxExpireTime The maximum expiration time.
*
* @return int|null The unix timestamp for when the element should expire.
* Will be NULL if no limit is set for the element.
*/
private static function getExpireTime(mixed $element, ?int $maxExpireTime): ?int
{
// validUntil may be null
$expire = $element->getValidUntil();
if ($maxExpireTime !== null && ($expire === null || $maxExpireTime < $expire)) {
$expire = $maxExpireTime;
}
return $expire;
}
/**
* This function returns the entity id of this parsed entity.
*
* @return string The entity id of this parsed entity.
*/
public function getEntityId(): string
{
return $this->entityId;
}
/**
* @return array
*/
private function getMetadataCommon(): array
{
$ret = [];
$ret['entityid'] = $this->entityId;
// add organizational metadata
if (!empty($this->organizationName)) {
$ret['description'] = $this->organizationName;
$ret['OrganizationName'] = $this->organizationName;
}
if (!empty($this->organizationDisplayName)) {
$ret['name'] = $this->organizationDisplayName;
$ret['OrganizationDisplayName'] = $this->organizationDisplayName;
}
if (!empty($this->organizationURL)) {
$ret['url'] = $this->organizationURL;
$ret['OrganizationURL'] = $this->organizationURL;
}
// add contact metadata
if (!empty($this->contacts)) {
$ret['contacts'] = $this->contacts;
}
return $ret;
}
/**
* Add data parsed from extensions to metadata.
*
* @param array &$metadata The metadata that should be updated.
* @param array $roleDescriptor The parsed role descriptor.
*/
private function addExtensions(array &$metadata, array $roleDescriptor): void
{
Assert::keyExists($roleDescriptor, 'scope');
$scopes = array_merge($this->scopes, array_diff($roleDescriptor['scope'], $this->scopes));
if (!empty($scopes)) {
$metadata['scope'] = $scopes;
}
if (!empty($this->registrationInfo)) {
$metadata['RegistrationInfo'] = $this->registrationInfo;
}
if (!empty($this->entityAttributes)) {
$metadata['EntityAttributes'] = $this->entityAttributes;
// check for entity categories
if (Utils\Config\Metadata::isHiddenFromDiscovery($metadata)) {
$metadata['hide.from.discovery'] = true;
}
}
if (!empty($roleDescriptor['DiscoveryResponse'])) {
$metadata['DiscoveryResponse'] = $roleDescriptor['DiscoveryResponse'];
}
if (!empty($roleDescriptor['UIInfo'])) {
$metadata['UIInfo'] = $roleDescriptor['UIInfo'];
}
if (!empty($roleDescriptor['DiscoHints'])) {
$metadata['DiscoHints'] = $roleDescriptor['DiscoHints'];
}
}
/**
* This function returns the metadata for SAML 2.0 SPs in the format SimpleSAMLphp expects.
* This is an associative array with the following fields:
* - 'entityid': The entity id of the entity described in the metadata.
* - 'AssertionConsumerService': String with the URL of the assertion consumer service which supports
* the browser-post binding.
* - 'SingleLogoutService': String with the URL where we should send logout requests/responses.
* - 'NameIDFormat': The name ID format this SP expects. This may be unset.
* - 'keys': X509Certificate(s) for entity (if present).
*
* Metadata must be loaded with one of the parse functions before this function can be called.
*
* @return array|null An associative array with metadata or NULL if we are unable to
* generate metadata for a SAML 2.x SP.
*/
public function getMetadata20SP(): ?array
{
$ret = $this->getMetadataCommon();
$ret['metadata-set'] = 'saml20-sp-remote';
// find SP information which supports the SAML 2.0 protocol
$spd = $this->getSPDescriptors(self::$SAML20Protocols);
if (count($spd) === 0) {
return null;
}
// we currently only look at the first SPDescriptor which supports SAML 2.0
$spd = $spd[0];
// add expire time to metadata
if (array_key_exists('expire', $spd)) {
$ret['expire'] = $spd['expire'];
}
// find the assertion consumer service endpoints
$ret['AssertionConsumerService'] = $spd['AssertionConsumerService'];
// find the single logout service endpoint
$ret['SingleLogoutService'] = $spd['SingleLogoutService'];
// find the NameIDFormat. This may not exist
if (count($spd['nameIDFormats']) > 0) {
// SimpleSAMLphp currently only supports a single NameIDFormat per SP. We use the first one
$ret['NameIDFormat'] = $spd['nameIDFormats'][0];
}
// add the list of attributes the SP should receive
if (array_key_exists('attributes', $spd)) {
$ret['attributes'] = $spd['attributes'];
}
if (array_key_exists('attributes.required', $spd)) {
$ret['attributes.required'] = $spd['attributes.required'];
}
if (array_key_exists('attributes.NameFormat', $spd)) {
$ret['attributes.NameFormat'] = $spd['attributes.NameFormat'];
}
if (array_key_exists('attributes.index', $spd)) {
$ret['attributes.index'] = $spd['attributes.index'];
}
if (array_key_exists('attributes.isDefault', $spd)) {
$ret['attributes.isDefault'] = $spd['attributes.isDefault'];
}
// add name & description
if (array_key_exists('name', $spd)) {
$ret['name'] = $spd['name'];
}
if (array_key_exists('description', $spd)) {
$ret['description'] = $spd['description'];
}
// add public keys
if (!empty($spd['keys'])) {
$ret['keys'] = $spd['keys'];
}
// add validate.authnrequest
if (array_key_exists('AuthnRequestsSigned', $spd)) {
$ret['validate.authnrequest'] = $spd['AuthnRequestsSigned'];
}
// add saml20.sign.assertion
if (array_key_exists('WantAssertionsSigned', $spd)) {
$ret['saml20.sign.assertion'] = $spd['WantAssertionsSigned'];
}
// add extensions
$this->addExtensions($ret, $spd);
// prioritize mdui:DisplayName as the name if available
if (!empty($ret['UIInfo']['DisplayName'])) {
$ret['name'] = $ret['UIInfo']['DisplayName'];
}
return $ret;
}
/**
* This function returns the metadata for SAML 2.0 IdPs in the format SimpleSAMLphp expects.
* This is an associative array with the following fields:
* - 'entityid': The entity id of the entity described in the metadata.
* - 'name': Auto generated name for this entity. Currently set to the entity id.
* - 'SingleSignOnService': String with the URL of the SSO service which supports the redirect binding.
* - 'SingleLogoutService': String with the URL where we should send logout requests(/responses).
* - 'SingleLogoutServiceResponse': String where we should send logout responses (if this is different from
* the 'SingleLogoutService' endpoint.
* - 'NameIDFormats': The name ID formats this IdP supports.
* - 'keys': X509Certificate(s) for entity (if present).
*
* Metadata must be loaded with one of the parse functions before this function can be called.
*
* @return array|null An associative array with metadata or NULL if we are unable to
* generate metadata for a SAML 2.0 IdP.
*/
public function getMetadata20IdP(): ?array
{
$ret = $this->getMetadataCommon();
$ret['metadata-set'] = 'saml20-idp-remote';
// find IdP information which supports the SAML 2.0 protocol
$idp = $this->getIdPDescriptors(self::$SAML20Protocols);
if (count($idp) === 0) {
return null;
}
// we currently only look at the first IDP descriptor which supports SAML 2.0
$idp = $idp[0];
// add expire time to metadata
if (array_key_exists('expire', $idp)) {
$ret['expire'] = $idp['expire'];
}
// enable redirect.sign if WantAuthnRequestsSigned is enabled
if ($idp['WantAuthnRequestsSigned']) {
$ret['sign.authnrequest'] = true;
}
// find the SSO service endpoint
$ret['SingleSignOnService'] = $idp['SingleSignOnService'];
// find the single logout service endpoint
$ret['SingleLogoutService'] = $idp['SingleLogoutService'];
// find the ArtifactResolutionService endpoint
$ret['ArtifactResolutionService'] = $idp['ArtifactResolutionService'];
// add supported nameIDFormats
$ret['NameIDFormats'] = $idp['nameIDFormats'];
// add public keys
if (!empty($idp['keys'])) {
$ret['keys'] = $idp['keys'];
}
// add extensions
$this->addExtensions($ret, $idp);
// prioritize mdui:DisplayName as the name if available
if (!empty($ret['UIInfo']['DisplayName'])) {
$ret['name'] = $ret['UIInfo']['DisplayName'];
}
return $ret;
}
/**
* Retrieve AttributeAuthorities from the metadata.
*
* @return \SimpleSAML\SAML2\XML\md\AttributeAuthorityDescriptor[] Array of AttributeAuthorityDescriptor entries.
*/
public function getAttributeAuthorities(): array
{
return $this->attributeAuthorityDescriptors;
}
/**
* Parse a RoleDescriptorType element.
*
* The returned associative array has the following elements:
* - 'protocols': Array with the protocols supported.
* - 'expire': Timestamp for when this descriptor expires.
* - 'keys': Array of associative arrays with the elements from parseKeyDescriptor.
*
* @param \SimpleSAML\SAML2\XML\md\RoleDescriptor $element The element we should extract metadata from.
* @param int|null $expireTime The unix timestamp for when this element should expire, or
* NULL if unknown.
*
* @return array An associative array with metadata we have extracted from this element.
* @throws \Exception
*/
private static function parseRoleDescriptorType(RoleDescriptor $element, ?int $expireTime): array
{
$ret = [];
$expireTime = self::getExpireTime($element, $expireTime);
if ($expireTime !== null) {
// we got an expired timestamp, either from this element or one of the parent elements
$ret['expire'] = $expireTime;
}
$ret['protocols'] = $element->getProtocolSupportEnumeration();
// process KeyDescriptor elements
$ret['keys'] = [];
foreach ($element->getKeyDescriptor() as $kd) {
$key = self::parseKeyDescriptor($kd);
if ($key !== null) {
$ret['keys'][] = $key;
}
}
$ext = self::processExtensions($element);
$ret['scope'] = $ext['scope'];
$ret['EntityAttributes'] = $ext['EntityAttributes'];
$ret['DiscoveryResponse'] = $ext['DiscoveryResponse'];
$ret['UIInfo'] = $ext['UIInfo'];
$ret['DiscoHints'] = $ext['DiscoHints'];
return $ret;
}
/**
* This function extracts metadata from a SSODescriptor element.
*
* The returned associative array has the following elements:
* - 'protocols': Array with the protocols this SSODescriptor supports.
* - 'SingleLogoutService': Array with the single logout service endpoints. Each endpoint is stored
* as an associative array with the elements that parseGenericEndpoint returns.
* - 'nameIDFormats': The NameIDFormats supported by this SSODescriptor. This may be an empty array.
* - 'keys': Array of associative arrays with the elements from parseKeyDescriptor:
*
* @param \SAML2\XML\md\SSODescriptorType $element The element we should extract metadata from.
* @param int|null $expireTime The unix timestamp for when this element should expire, or NULL if unknown.
*
* @return array An associative array with metadata we have extracted from this element.
* @throws \Exception
*/
private static function parseSSODescriptor(SSODescriptorType $element, ?int $expireTime): array
{
$sd = self::parseRoleDescriptorType($element, $expireTime);
// find all SingleLogoutService elements
$sd['SingleLogoutService'] = self::extractEndpoints($element->getSingleLogoutService());
// find all ArtifactResolutionService elements
$sd['ArtifactResolutionService'] = self::extractEndpoints($element->getArtifactResolutionService());
// process NameIDFormat elements
$sd['nameIDFormats'] = [];
foreach ($element->getNameIDFormat() as $format) {
$sd['nameIDFormats'][] = $format->getContent();
}
return $sd;
}
/**
* This function extracts metadata from a SPSSODescriptor element.
*
* @param \SimpleSAML\SAML2\XML\md\SPSSODescriptor $element The element which should be parsed.
* @param int|null $expireTime The unix timestamp for when this element should expire, or NULL if unknown.
* @throws \Exception
*/
private function processSPSSODescriptor(SPSSODescriptor $element, ?int $expireTime): void
{
$sp = self::parseSSODescriptor($element, $expireTime);
// find all AssertionConsumerService elements
$sp['AssertionConsumerService'] = self::extractEndpoints($element->getAssertionConsumerService());
// find all the attributes and SP name...
$attcs = $element->getAttributeConsumingService();
if (count($attcs) > 0) {
self::parseAttributeConsumerService($attcs[0], $sp);
}
// check AuthnRequestsSigned
if ($element->getAuthnRequestsSigned() !== null) {
$sp['AuthnRequestsSigned'] = $element->getAuthnRequestsSigned();
}
// check WantAssertionsSigned
if ($element->wantAssertionsSigned() !== null) {
$sp['WantAssertionsSigned'] = $element->wantAssertionsSigned();
}
$this->spDescriptors[] = $sp;
}
/**
* This function extracts metadata from a IDPSSODescriptor element.
*
* @param \SimpleSAML\SAML2\XML\md\IDPSSODescriptor $element The element which should be parsed.
* @param int|null $expireTime The unix timestamp for when this element should expire, or NULL if unknown.
* @throws \Exception
*/
private function processIDPSSODescriptor(IDPSSODescriptor $element, ?int $expireTime): void
{
$idp = self::parseSSODescriptor($element, $expireTime);
// find all SingleSignOnService elements
$idp['SingleSignOnService'] = self::extractEndpoints($element->getSingleSignOnService());
if ($element->wantAuthnRequestsSigned()) {
$idp['WantAuthnRequestsSigned'] = true;
} else {
$idp['WantAuthnRequestsSigned'] = false;
}
$this->idpDescriptors[] = $idp;
}
/**
* This function extracts metadata from a AttributeAuthorityDescriptor element.
*
* @param \SimpleSAML\SAML2\XML\md\AttributeAuthorityDescriptor $element The element which should be parsed.
* @param int|null $expireTime The unix timestamp for when this element should expire, or NULL if unknown.
* @throws \Exception
*/
private function processAttributeAuthorityDescriptor(
AttributeAuthorityDescriptor $element,
?int $expireTime,
): void {
$aad = self::parseRoleDescriptorType($element, $expireTime);
$aad['entityid'] = $this->getEntityId();
$aad['metadata-set'] = 'attributeauthority-remote';
$aad['AttributeService'] = self::extractEndpoints($element->getAttributeService());
$aad['AssertionIDRequestService'] = self::extractEndpoints($element->getAssertionIDRequestService());
$aad['NameIDFormat'] = $element->getNameIDFormat();
$this->attributeAuthorityDescriptors[] = $aad;
}
/**
* Parse an Extensions element. Extensions may appear in multiple elements and certain extension may get inherited
* from a parent element.
*
* @param mixed $element The element which contains the Extensions element.
* @param array $parentExtensions An optional array of extensions from the parent element.
*
* @return array An associative array with the extensions parsed.
* @throws \Exception
*/
private static function processExtensions(mixed $element, array $parentExtensions = []): array
{
$ret = [
'scope' => [],
'EntityAttributes' => [],
'RegistrationInfo' => [],
'DiscoveryResponse' => [],
'UIInfo' => [],
'DiscoHints' => [],
];
// Some extensions may get inherited from a parent element
if (
($element instanceof EntityDescriptor
|| $element instanceof EntitiesDescriptor)
&& !empty($parentExtensions['RegistrationInfo'])
) {
$ret['RegistrationInfo'] = $parentExtensions['RegistrationInfo'];
}
$extensions = $element->getExtensions()?->getList() ?? [];
foreach ($extensions as $e) {
if ($e instanceof Scope) {
$ret['scope'][] = $e->getContent();
continue;
}
// Entity Attributes are only allowed at entity level extensions and not at RoleDescriptor level
if (
$element instanceof EntityDescriptor
|| $element instanceof EntitiesDescriptor
) {
if ($e instanceof RegistrationInfo) {
// Registration Authority cannot be overridden (warn only if override attempts to change the value)
if (
isset($ret['RegistrationInfo']['registrationAuthority'])
&& $ret['RegistrationInfo']['registrationAuthority'] !== $e->getRegistrationAuthority()
) {
Logger::warning(sprintf(
'Invalid attempt to override registrationAuthority \'%s\' with \'%s\'',
$ret['RegistrationInfo']['registrationAuthority'],
$e->getRegistrationAuthority(),
));
} else {
$ret['RegistrationInfo'] = $e->toArray();
}
}
if ($e instanceof EntityAttributes && !empty($e->getChildren())) {
foreach ($e->getChildren() as $attr) {
// only saml:Attribute are currently supported here. The specifications also allows
// saml:Assertions, which more complex processing
if ($attr instanceof Attribute) {
$attrName = $attr->getName();
$attrNameFormat = $attr->getNameFormat();
$attrValue = $attr->getAttributeValues();
if ($attrValue === []) {
continue;
}
// attribute names that is not URI is prefixed as this: '{nameformat}name'
$name = $attrName;
if ($attrNameFormat === null) {
$name = '{' . C::NAMEFORMAT_UNSPECIFIED . '}' . $attrName;
} elseif ($attrNameFormat !== C::NAMEFORMAT_URI) {
$name = '{' . $attrNameFormat . '}' . $attrName;
}
$values = [];
foreach ($attrValue as $attrval) {
$values[] = $attrval->getValue();
}
$ret['EntityAttributes'][$name] = $values;
}
}
}
}
// DiscoveryResponse elements only make sense at SPSSODescriptor level extensions
if ($element instanceof SPSSODescriptor) {
if ($e instanceof DiscoveryResponse) {
$ret['DiscoveryResponse'] = array_merge($ret['DiscoveryResponse'], self::extractEndpoints([$e]));
}
}
// UIInfo elements are only allowed at RoleDescriptor level extensions
if ($element instanceof AbstractRoleDescriptorType) {
if ($e instanceof UIInfo) {
$ret['UIInfo'] = $e->toArray();
}
}
// DiscoHints elements are only allowed at IDPSSODescriptor level extensions
if ($element instanceof IDPSSODescriptor) {
if ($e instanceof DiscoHints) {
$ret['DiscoHints'] = $e->toArray();
}
}
}
return $ret;
}
/**
* Parse and process a Organization element.
*
* @param \SimpleSAML\SAML2\XML\md\Organization $element The Organization element.
*/
private function processOrganization(Organization $element): void
{
$org = $element->toArray();
$this->organizationName = $org['OrganizationName'];
$this->organizationDisplayName = $org['OrganizationDisplayName'];
$this->organizationURL = $org['OrganizationURL'];
}