forked from simplesamlphp/simplesamlphp-module-adfs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetadataBuilder.php
More file actions
403 lines (344 loc) · 13.5 KB
/
MetadataBuilder.php
File metadata and controls
403 lines (344 loc) · 13.5 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
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\adfs\IdP;
use Beste\Clock\LocalizedClock;
use Exception;
use Psr\Clock\ClockInterface;
use SimpleSAML\Assert\Assert;
use SimpleSAML\Configuration;
use SimpleSAML\Logger;
use SimpleSAML\Module;
use SimpleSAML\SAML2\Exception\ArrayValidationException;
use SimpleSAML\SAML2\XML\md\AbstractMetadataDocument;
use SimpleSAML\SAML2\XML\md\ContactPerson;
use SimpleSAML\SAML2\XML\md\EntityDescriptor;
use SimpleSAML\SAML2\XML\md\Extensions;
use SimpleSAML\SAML2\XML\md\KeyDescriptor;
use SimpleSAML\SAML2\XML\md\Organization;
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\saml\AttributeValue;
use SimpleSAML\SAML2\XML\shibmd\Scope;
use SimpleSAML\Utils;
use SimpleSAML\WSSecurity\Constants as C;
use SimpleSAML\WSSecurity\XML\fed\PassiveRequestorEndpoint;
use SimpleSAML\WSSecurity\XML\fed\SecurityTokenServiceEndpoint;
use SimpleSAML\WSSecurity\XML\fed\SecurityTokenServiceType;
use SimpleSAML\WSSecurity\XML\fed\TokenType;
use SimpleSAML\WSSecurity\XML\fed\TokenTypesOffered;
use SimpleSAML\WSSecurity\XML\wsa_200508\Address;
use SimpleSAML\WSSecurity\XML\wsa_200508\EndpointReference;
use SimpleSAML\XML\Chunk;
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
use SimpleSAML\XMLSecurity\Key\PrivateKey;
use SimpleSAML\XMLSecurity\XML\ds\KeyInfo;
use SimpleSAML\XMLSecurity\XML\ds\KeyName;
use SimpleSAML\XMLSecurity\XML\ds\X509Certificate;
use SimpleSAML\XMLSecurity\XML\ds\X509Data;
use function array_key_exists;
use function preg_match;
/**
* Common code for building SAML 2 metadata based on the available configuration.
*
* @package simplesamlphp/simplesamlphp-module-adfs
*/
class MetadataBuilder
{
/** @var \Psr\Clock\ClockInterface */
protected ClockInterface $clock;
/**
* Constructor.
*
* @param \SimpleSAML\Configuration $config The general configuration
* @param \SimpleSAML\Configuration $metadata The metadata configuration
*/
public function __construct(
protected Configuration $config,
protected Configuration $metadata,
) {
$this->clock = LocalizedClock::in('Z');
}
/**
* Build a metadata document
*
* @return \SimpleSAML\SAML2\XML\md\EntityDescriptor
*/
public function buildDocument(): EntityDescriptor
{
$entityId = $this->metadata->getString('entityid');
$contactPerson = $this->getContactPerson();
$organization = $this->getOrganization();
$roleDescriptor = $this->getRoleDescriptor();
$randomUtils = new Utils\Random();
$entityDescriptor = new EntityDescriptor(
id: $randomUtils->generateID(),
entityId: $entityId,
contactPerson: $contactPerson,
organization: $organization,
roleDescriptor: $roleDescriptor,
);
if ($this->config->getOptionalBoolean('metadata.sign.enable', false) === true) {
$this->signDocument($entityDescriptor);
}
return $entityDescriptor;
}
/**
* @param \SimpleSAML\SAML2\XML\md\AbstractMetadataDocument $document
* @return \SimpleSAML\SAML2\XML\md\AbstractMetadataDocument
*/
protected function signDocument(AbstractMetadataDocument $document): AbstractMetadataDocument
{
$cryptoUtils = new Utils\Crypto();
/** @var array<mixed> $keyArray */
$keyArray = $cryptoUtils->loadPrivateKey($this->config, true, 'metadata.sign.');
$certArray = $cryptoUtils->loadPublicKey($this->config, false, 'metadata.sign.');
$algo = $this->config->getOptionalString('metadata.sign.algorithm', C::SIG_RSA_SHA256);
$key = PrivateKey::fromFile($keyArray['PEM'], $keyArray['password'] ?? '');
$signer = (new SignatureAlgorithmFactory())->getAlgorithm($algo, $key);
$keyInfo = null;
if ($certArray !== null) {
$keyInfo = new KeyInfo([
new X509Data([
new X509Certificate($certArray['certData']),
]),
]);
}
$document->sign($signer, C::C14N_EXCLUSIVE_WITHOUT_COMMENTS, $keyInfo);
return $document;
}
/**
* This method builds the md:Organization element, if any
*
* @return \SimpleSAML\SAML2\XML\md\Organization
*/
private function getOrganization(): ?Organization
{
if (
!$this->metadata->hasValue('OrganizationName') ||
!$this->metadata->hasValue('OrganizationDisplayName') ||
!$this->metadata->hasValue('OrganizationURL')
) {
// empty or incomplete organization information
return null;
}
$arrayUtils = new Utils\Arrays();
$org = null;
try {
$org = Organization::fromArray([
'OrganizationName' => $arrayUtils->arrayize($this->metadata->getArray('OrganizationName'), 'en'),
'OrganizationDisplayName' => $arrayUtils->arrayize(
$this->metadata->getArray('OrganizationDisplayName'),
'en',
),
'OrganizationURL' => $arrayUtils->arrayize($this->metadata->getArray('OrganizationURL'), 'en'),
]);
} catch (ArrayValidationException $e) {
Logger::error('Federation: invalid content found in contact: ' . $e->getMessage());
}
return $org;
}
/**
* This method builds the role descriptor elements
*
* @return \SimpleSAML\SAML2\XML\md\AbstractRoleDescriptor[]
*/
private function getRoleDescriptor(): array
{
$descriptors = [];
$set = $this->metadata->getString('metadata-set');
switch ($set) {
case 'adfs-idp-hosted':
$descriptors[] = $this->getSecurityTokenService();
break;
default:
throw new Exception('Not implemented');
}
return $descriptors;
}
/**
* This method builds the SecurityTokenService element
*
* @return \SimpleSAML\WSSecurity\XML\fed\SecurityTokenServiceType
*/
public function getSecurityTokenService(): SecurityTokenServiceType
{
$defaultEndpoint = Module::getModuleURL('adfs') . '/idp/prp.php';
$stsEndpoints = [
new SecurityTokenServiceEndpoint([
new EndpointReference(new Address($defaultEndpoint)),
]),
];
if ($this->config->getOptionalBoolean('adfs.mex_in_metadata', true)) {
$mexEndpoint = Module::getModuleURL('adfs') . '/ws-trust/mex';
$stsEndpoints[] = new SecurityTokenServiceEndpoint([
new EndpointReference(new Address($mexEndpoint)),
]);
}
if ($this->config->getOptionalBoolean('adfs.certificatemixed_in_metadata', false)) {
$certEndpoint = Module::getModuleURL('adfs') . '/ws-trust/2005/services/certificatemixed';
$stsEndpoints[] = new SecurityTokenServiceEndpoint([
new EndpointReference(new Address($certEndpoint)),
]);
}
if ($this->config->getOptionalBoolean('adfs.usernamemixed_in_metadata', false)) {
$unEndpoint = Module::getModuleURL('adfs') . '/ws-trust/2005/services/usernamemixed';
$stsEndpoints[] = new SecurityTokenServiceEndpoint([
new EndpointReference(new Address($unEndpoint)),
]);
}
return new SecurityTokenServiceType(
protocolSupportEnumeration: [C::NS_TRUST_200512, C::NS_TRUST_200502, C::NS_FED],
keyDescriptors: $this->getKeyDescriptor(),
tokenTypesOffered: new TokenTypesOffered([new TokenType('urn:oasis:names:tc:SAML:1.0:assertion')]),
securityTokenServiceEndpoint: $stsEndpoints,
passiveRequestorEndpoint: [
new PassiveRequestorEndpoint([
new EndpointReference(new Address($defaultEndpoint)),
]),
],
);
}
/**
* This method builds the md:KeyDescriptor elements, if any
*
* @return \SimpleSAML\SAML2\XML\md\KeyDescriptor[]
*/
private function getKeyDescriptor(): array
{
$keyDescriptor = [];
$keys = $this->metadata->getPublicKeys();
foreach ($keys as $key) {
if ($key['type'] !== 'X509Certificate') {
continue;
}
if (!isset($key['signing']) || $key['signing'] === true) {
$keyDescriptor[] = self::buildKeyDescriptor(
'signing',
$key['X509Certificate'],
$key['name'] ?? null,
);
}
if (!isset($key['encryption']) || $key['encryption'] === true) {
$keyDescriptor[] = self::buildKeyDescriptor(
'encryption',
$key['X509Certificate'],
$key['name'] ?? null,
);
}
}
if ($this->metadata->hasValue('https.certData')) {
$keyDescriptor[] = self::buildKeyDescriptor('signing', $this->metadata->getString('https.certData'), null);
}
return $keyDescriptor;
}
/**
* This method builds the md:ContactPerson elements, if any
*
* @return \SimpleSAML\SAML2\XML\md\ContactPerson[]
*/
private function getContactPerson(): array
{
$contacts = [];
foreach ($this->metadata->getOptionalArray('contacts', []) as $contact) {
if (array_key_exists('ContactType', $contact) && array_key_exists('EmailAddress', $contact)) {
$contacts[] = ContactPerson::fromArray($contact);
}
}
return $contacts;
}
/**
* This method builds the md:Extensions, if any
*
* @return \SimpleSAML\SAML2\XML\md\Extensions|null
*/
private function getExtensions(): ?Extensions
{
$extensions = [];
if ($this->metadata->hasValue('scope')) {
foreach ($this->metadata->getArray('scope') as $scopetext) {
$isRegexpScope = (1 === preg_match('/[\$\^\)\(\*\|\\\\]/', $scopetext));
$extensions[] = new Scope($scopetext, $isRegexpScope);
}
}
if ($this->metadata->hasValue('EntityAttributes')) {
$attr = [];
foreach ($this->metadata->getArray('EntityAttributes') as $attributeName => $attributeValues) {
$attrValues = [];
foreach ($attributeValues as $attributeValue) {
$attrValues[] = new AttributeValue($attributeValue);
}
// Attribute names that is not URI is prefixed as this: '{nameformat}name'
if (preg_match('/^\{(.*?)\}(.*)$/', $attributeName, $matches)) {
$attr[] = new Attribute(
name: $matches[2],
nameFormat: $matches[1] === C::NAMEFORMAT_UNSPECIFIED ? null : $matches[1],
attributeValue: $attrValues,
);
} else {
$attr[] = new Attribute(
name: $attributeName,
nameFormat: C::NAMEFORMAT_UNSPECIFIED,
attributeValue: $attrValues,
);
}
}
$extensions[] = new EntityAttributes($attr);
}
if ($this->metadata->hasValue('saml:Extensions')) {
$chunks = $this->metadata->getArray('saml:Extensions');
Assert::allIsInstanceOf($chunks, Chunk::class);
$extensions = array_merge($extensions, $chunks);
}
if ($this->metadata->hasValue('RegistrationInfo')) {
try {
$extensions[] = RegistrationInfo::fromArray($this->metadata->getArray('RegistrationInfo'));
} catch (ArrayValidationException $err) {
Logger::error('Metadata: invalid content found in RegistrationInfo: ' . $err->getMessage());
}
}
if ($this->metadata->hasValue('UIInfo')) {
try {
$extensions[] = UIInfo::fromArray($this->metadata->getArray('UIInfo'));
} catch (ArrayValidationException $err) {
Logger::error('Metadata: invalid content found in UIInfo: ' . $err->getMessage());
}
}
if ($this->metadata->hasValue('DiscoHints')) {
try {
$extensions[] = DiscoHints::fromArray($this->metadata->getArray('DiscoHints'));
} catch (ArrayValidationException $err) {
Logger::error('Metadata: invalid content found in DiscoHints: ' . $err->getMessage());
}
}
if ($extensions !== []) {
return new Extensions($extensions);
}
return null;
}
/**
* @param string $use
* @param string $x509Cert
* @param string|null $keyName
*
* @return \SimpleSAML\SAML2\XML\md\KeyDescriptor
*/
private static function buildKeyDescriptor(string $use, string $x509Cert, ?string $keyName): KeyDescriptor
{
Assert::oneOf($use, ['encryption', 'signing']);
$info = [
new X509Data([
new X509Certificate($x509Cert),
]),
];
if ($keyName !== null) {
$info[] = new KeyName($keyName);
}
return new KeyDescriptor(
new KeyInfo($info),
$use,
);
}
}