-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAttributeServer.php
More file actions
308 lines (268 loc) · 10.7 KB
/
AttributeServer.php
File metadata and controls
308 lines (268 loc) · 10.7 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
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\exampleattributeserver\Controller;
use DateInterval;
use Nyholm\Psr7\Factory\Psr17Factory;
use SimpleSAML\{Configuration, Error, Logger};
use SimpleSAML\HTTP\RunnableResponse;
use SimpleSAML\Metadata\MetaDataStorageHandler;
use SimpleSAML\SAML2\Binding;
use SimpleSAML\SAML2\Binding\HTTPPost;
use SimpleSAML\SAML2\Constants as C;
use SimpleSAML\SAML2\Utils as SAML2_Utils;
use SimpleSAML\SAML2\XML\saml\{
Assertion,
Attribute,
AttributeStatement,
AttributeValue,
Audience,
AudienceRestriction,
Conditions,
Issuer,
Subject,
SubjectConfirmation,
SubjectConfirmationData,
};
use SimpleSAML\SAML2\XML\samlp\{AttributeQuery, Response, Status, StatusCode};
use SimpleSAML\Utils;
use SimpleSAML\XML\Utils\Random;
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
use SimpleSAML\XMLSecurity\Key\PrivateKey;
use SimpleSAML\XMLSecurity\XML\ds\{KeyInfo, X509Certificate, X509Data};
use SimpleSAML\XMLSecurity\XML\SignableElementInterface;
use Symfony\Bridge\PsrHttpMessage\Factory\{HttpFoundationFactory, PsrHttpFactory};
use Symfony\Component\HttpFoundation\Request;
use function array_filter;
/**
* Controller class for the exampleattributeserver module.
*
* This class serves the attribute server available in the module.
*
* @package SimpleSAML\Module\exampleattributeserver
*/
class AttributeServer
{
/** @var \SimpleSAML\Configuration */
protected Configuration $config;
/** @var \SimpleSAML\Metadata\MetaDataStorageHandler|null */
protected ?MetaDataStorageHandler $metadataHandler = null;
/**
* ConfigController constructor.
*
* @param \SimpleSAML\Configuration $config The configuration to use.
*/
public function __construct(Configuration $config)
{
$this->config = $config;
}
/**
* Inject the \SimpleSAML\Metadata\MetaDataStorageHandler dependency.
*
* @param \SimpleSAML\Metadata\MetaDataStorageHandler $handler
*/
public function setMetadataStorageHandler(MetaDataStorageHandler $handler): void
{
$this->metadataHandler = $handler;
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request The current request.
*
* @return \SimpleSAML\HTTP\RunnableResponse
* @throws \SimpleSAML\Error\BadRequest
*/
public function main(/** @scrutinizer ignore-unused */ Request $request): RunnableResponse
{
$psr17Factory = new Psr17Factory();
$psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory);
$psrRequest = $psrHttpFactory->createRequest($request);
$binding = Binding::getCurrentBinding($psrRequest);
$message = $binding->receive($psrRequest);
if (!($message instanceof AttributeQuery)) {
throw new Error\BadRequest('Invalid message received to AttributeQuery endpoint.');
}
$idpEntityId = $this->metadataHandler->getMetaDataCurrentEntityID('saml20-idp-hosted');
$issuer = $message->getIssuer();
if ($issuer === null) {
throw new Error\BadRequest('Missing <saml:Issuer> in <samlp:AttributeQuery>.');
} else {
$spEntityId = $issuer->getContent();
if ($spEntityId === '') {
throw new Error\BadRequest('Empty <saml:Issuer> in <samlp:AttributeQuery>.');
}
}
$idpMetadata = $this->metadataHandler->getMetaDataConfig($idpEntityId, 'saml20-idp-hosted');
$spMetadata = $this->metadataHandler->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
// The endpoint we should deliver the message to
$endpoint = $spMetadata->getString('testAttributeEndpoint');
// The attributes we will return
$attributes = [
new Attribute(
'name',
C::NAMEFORMAT_UNSPECIFIED,
null,
[
new AttributeValue('value1'),
new AttributeValue('value2'),
new AttributeValue('value3'),
],
),
new Attribute(
'test',
C::NAMEFORMAT_UNSPECIFIED,
null,
[
new AttributeValue('test'),
],
),
];
// Determine which attributes we will return
// @phpstan-ignore identical.alwaysFalse
if (count($attributes) === 0) {
Logger::debug('No attributes requested - return all attributes.');
$attributeStatement = null;
} else {
$returnAttributes = [];
foreach ($message->getAttributes() as $reqAttr) {
foreach ($attributes as $attr) {
if (
$attr->getName() === $reqAttr->getName()
&& $attr->getNameFormat() === $reqAttr->getNameFormat()
) {
// The requested attribute is available
if ($reqAttr->getAttributeValues() === []) {
// If no specific values are requested, return all
$returnAttributes[] = $attr;
} else {
$returnValues = $this->filterAttributeValues(
$reqAttr->getAttributeValues(),
$attr->getAttributeValues(),
);
$returnAttributes[] = new Attribute(
$attr->getName(),
$attr->getNameFormat(),
null,
$returnValues,
$attr->getAttributesNS(),
);
}
}
}
}
$attributeStatement = $returnAttributes ? (new AttributeStatement($returnAttributes)) : null;
}
// $returnAttributes contains the attributes we should return. Send them
$clock = SAML2_Utils::getContainer()->getClock();
$statements = array_filter([$attributeStatement]);
$assertion = new Assertion(
issuer: new Issuer($idpEntityId),
issueInstant: $clock->now(),
id: (new Random())->generateID(),
subject: new Subject(
identifier: $message->getSubject()->getIdentifier(),
subjectConfirmation: [
new SubjectConfirmation(
method: C::CM_BEARER,
subjectConfirmationData: new SubjectConfirmationData(
notOnOrAfter: $clock->now()->add(new DateInterval('PT300S')),
recipient: $endpoint,
inResponseTo: $message->getId(),
),
),
],
),
conditions: new Conditions(
notBefore: $clock->now(),
notOnOrAfter: $clock->now()->add(new DateInterval('PT300S')),
audienceRestriction: [
new AudienceRestriction([
new Audience($spEntityId),
]),
],
),
statements: $statements,
);
self::addSign($idpMetadata, $spMetadata, $assertion);
$response = new Response(
status: new Status(
new StatusCode(C::STATUS_SUCCESS),
),
issueInstant: $clock->now(),
issuer: $issuer,
id: (new Random())->generateID(),
version: '2.0',
inResponseTo: $message->getId(),
destination: $endpoint,
assertions: [$assertion],
);
self::addSign($idpMetadata, $spMetadata, $response);
/** @var \SimpleSAML\SAML2\Binding\HTTPPost $httpPost */
$httpPost = new HTTPPost();
$httpPost->setRelayState($binding->getRelayState());
return new RunnableResponse([$httpPost, 'send'], [$response]);
}
/**
* @param array<\SimpleSAML\SAML2\XML\saml\AttributeValue> $reqValues
* @param array<\SimpleSAML\SAML2\XML\saml\AttributeValue> $values
*
* @return array<\SimpleSAML\SAML2\XML\saml\AttributeValue>
*/
private function filterAttributeValues(array $reqValues, array $values): array
{
$result = [];
foreach ($reqValues as $x) {
foreach ($values as $y) {
if ($x->getValue() === $y->getValue()) {
$result[] = $y;
}
}
}
return $result;
}
/**
* @deprecated This method is a modified version of \SimpleSAML\Module\saml\Message::addSign and
* should be replaced with a call to a future ServiceProvider-class in the saml2-library
*
* Add signature key and sender certificate to an element (Message or Assertion).
*
* @param \SimpleSAML\Configuration $srcMetadata The metadata of the sender.
* @param \SimpleSAML\Configuration $dstMetadata The metadata of the recipient.
* @param \SimpleSAML\XMLSecurity\XML\SignableElementInterface $element The element we should add the data to.
*/
private static function addSign(
Configuration $srcMetadata,
Configuration $dstMetadata,
SignableElementInterface &$element,
): void {
$dstPrivateKey = $dstMetadata->getOptionalString('signature.privatekey', null);
$cryptoUtils = new Utils\Crypto();
if ($dstPrivateKey !== null) {
/** @var string[] $keyArray */
$keyArray = $cryptoUtils->loadPrivateKey($dstMetadata, true, 'signature.');
$certArray = $cryptoUtils->loadPublicKey($dstMetadata, false, 'signature.');
} else {
/** @var string[] $keyArray */
$keyArray = $cryptoUtils->loadPrivateKey($srcMetadata, true);
$certArray = $cryptoUtils->loadPublicKey($srcMetadata, false);
}
$algo = $dstMetadata->getOptionalString('signature.algorithm', null);
if ($algo === null) {
$algo = $srcMetadata->getOptionalString('signature.algorithm', C::SIG_RSA_SHA256);
}
$privateKey = PrivateKey::fromFile($keyArray['PEM'], $keyArray['password']);
$keyInfo = null;
if ($certArray !== null) {
$keyInfo = new KeyInfo([
new X509Data(
[
new X509Certificate($certArray['PEM']),
],
),
]);
}
$signer = (new SignatureAlgorithmFactory())->getAlgorithm(
$algo,
$privateKey,
);
$element->sign($signer, C::C14N_EXCLUSIVE_WITHOUT_COMMENTS, $keyInfo);
}
}