forked from simplesamlphp/saml2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPArtifact.php
More file actions
300 lines (246 loc) · 10.2 KB
/
Copy pathHTTPArtifact.php
File metadata and controls
300 lines (246 loc) · 10.2 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
<?php
declare(strict_types=1);
namespace SimpleSAML\SAML2\Binding;
use DateInterval;
use Exception;
use Nyholm\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use SimpleSAML\Configuration;
use SimpleSAML\Metadata\MetaDataStorageHandler;
use SimpleSAML\Module\saml\Message as MSG;
use SimpleSAML\SAML2\Assert\Assert;
use SimpleSAML\SAML2\Binding;
use SimpleSAML\SAML2\Compat\ContainerSingleton;
use SimpleSAML\SAML2\SOAPClient;
use SimpleSAML\SAML2\Utils;
use SimpleSAML\SAML2\XML\saml\Issuer;
use SimpleSAML\SAML2\XML\samlp\AbstractMessage;
use SimpleSAML\SAML2\XML\samlp\Artifact;
use SimpleSAML\SAML2\XML\samlp\ArtifactResolve;
use SimpleSAML\SAML2\XML\samlp\ArtifactResponse;
use SimpleSAML\Store\StoreFactory;
use SimpleSAML\Utils\HTTP;
use SimpleSAML\XMLSecurity\Alg\Signature\SignatureAlgorithmFactory;
use SimpleSAML\XMLSecurity\Key\PublicKey;
use SimpleSAML\XMLSecurity\TestUtils\PEMCertificatesMock;
use function array_key_exists;
use function base64_decode;
use function base64_encode;
use function bin2hex;
use function chunk_split;
use function file_exists;
use function hexdec;
use function openssl_pkey_get_details;
use function openssl_pkey_get_public;
use function openssl_random_pseudo_bytes;
use function pack;
use function sha1;
use function substr;
use function var_export;
/**
* Class which implements the HTTP-Artifact binding.
*
* @package simplesamlphp/saml2
*/
class HTTPArtifact extends Binding implements AsynchronousBindingInterface, RelayStateInterface
{
use RelayStateTrait;
/**
* @var \SimpleSAML\Configuration
*/
private Configuration $spMetadata;
/**
* Create the redirect URL for a message.
*
* @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message The message.
* @return string The URL the user should be redirected to in order to send a message.
*
* @throws \Exception
*/
public function getRedirectURL(AbstractMessage $message): string
{
$config = Configuration::getInstance();
$store = StoreFactory::getInstance($config->getString('store.type'));
if ($store === false) {
throw new Exception('Unable to send artifact without a datastore configured.');
}
$generatedId = pack('H*', bin2hex(openssl_random_pseudo_bytes(20)));
$issuer = $message->getIssuer();
if ($issuer === null) {
throw new Exception('Cannot get redirect URL, no Issuer set in the message.');
}
$artifact = base64_encode(
"\x00\x04\x00\x00" . sha1($issuer->getContent()->getValue(), true) . $generatedId,
);
$artifactData = $message->toXML();
$artifactDataString = $artifactData->ownerDocument?->saveXML($artifactData);
$clock = Utils::getContainer()->getClock();
$store->set('artifact', $artifact, $artifactDataString, $clock->now()->add(new DateInterval('PT15M')));
$destination = $message->getDestination();
if ($destination === null) {
throw new Exception('Cannot get redirect URL, no destination set in the message.');
}
$params = ['SAMLart' => $artifact];
$relayState = $this->getRelayState();
if ($relayState !== null) {
$params['RelayState'] = $relayState;
}
$httpUtils = new HTTP();
return $httpUtils->addURLparameters($destination->getValue(), $params);
}
/**
* Send a SAML 2 message using the HTTP-Redirect binding.
*
* @param \SimpleSAML\SAML2\XML\samlp\AbstractMessage $message The message we should send.
* @return \Psr\Http\Message\ResponseInterface
*/
public function send(AbstractMessage $message): ResponseInterface
{
$destination = $this->getRedirectURL($message);
return new Response(303, ['Location' => $destination]);
}
/**
* Receive a SAML 2 message sent using the HTTP-Artifact binding.
*
* Throws an exception if it is unable receive the message.
*
* @param \Psr\Http\Message\ServerRequestInterface $request
* @return \SimpleSAML\SAML2\XML\samlp\AbstractMessage The received message.
*
* @throws \Exception
* @throws \SimpleSAML\Assert\AssertionFailedException if assertions are false
*/
public function receive(ServerRequestInterface $request): AbstractMessage
{
$query = $request->getQueryParams();
if (array_key_exists('SAMLart', $query)) {
$artifact = base64_decode($query['SAMLart'], true);
$endpointIndex = bin2hex(substr($artifact, 2, 2));
$sourceId = bin2hex(substr($artifact, 4, 20));
} else {
throw new Exception('Missing SAMLart parameter.');
}
$metadataHandler = MetaDataStorageHandler::getMetadataHandler();
$idpMetadata = $metadataHandler->getMetaDataConfigForSha1($sourceId, 'saml20-idp-remote');
if ($idpMetadata === null) {
throw new Exception('No metadata found for remote provider with SHA1 ID: ' . var_export($sourceId, true));
}
$endpoint = null;
foreach ($idpMetadata->getEndpoints('ArtifactResolutionService') as $ep) {
if ($ep['index'] === hexdec($endpointIndex)) {
$endpoint = $ep;
break;
}
}
if ($endpoint === null) {
throw new Exception('No ArtifactResolutionService with the correct index.');
}
Utils::getContainer()->getLogger()->debug(
"ArtifactResolutionService endpoint being used is := " . $endpoint['Location'],
);
Assert::notEmpty($this->spMetadata, 'Cannot process received message without SP metadata.');
/**
* Set the request attributes
*/
$issuer = new Issuer($this->spMetadata->getString('entityid'));
// Construct the ArtifactResolve Request
$ar = new ArtifactResolve(new Artifact($artifact), null, $issuer, null, '2.0', $endpoint['Location']);
// sign the request
MSG::addSign($this->spMetadata, $idpMetadata, $ar); // Shoaib - moved from the SOAPClient.
$soap = new SOAPClient();
// Send message through SoapClient
$artifactResponse = $soap->send($ar, $this->spMetadata, $idpMetadata);
if (!($artifactResponse instanceof ArtifactResponse)) {
throw new Exception('Invalid message received in response to our ArtifactResolve.');
}
if (!$artifactResponse->isSuccess()) {
throw new Exception('Received error from ArtifactResolutionService.');
}
$artifactResponse = $this->verifyArtifactResponseSignature($artifactResponse, $idpMetadata);
$samlResponse = $artifactResponse->getMessage();
if ($samlResponse === null) {
/* Empty ArtifactResponse - possibly because of Artifact replay? */
throw new Exception('Empty ArtifactResponse received, maybe a replay?');
}
$query = $request->getQueryParams();
if (isset($query['RelayState'])) {
$this->setRelayState($query['RelayState']);
}
if (!$samlResponse->isSigned()) {
return $samlResponse;
}
$container = ContainerSingleton::getInstance();
$blacklist = $container->getBlacklistedEncryptionAlgorithms();
$verifier = (new SignatureAlgorithmFactory($blacklist))->getAlgorithm(
$samlResponse->getSignature()->getSignedInfo()->getSignatureMethod()->getAlgorithm(),
// TODO: Need to use the key from the metadata
PEMCertificatesMock::getPublicKey(PEMCertificatesMock::SELFSIGNED_PUBLIC_KEY),
);
return $samlResponse->verify($verifier);
}
/**
* @param \SimpleSAML\Configuration $sp
*/
public function setSPMetadata(Configuration $sp): void
{
$this->spMetadata = $sp;
}
/**
* Verify the ArtifactResponse signature using IdP metadata keys.
*
* Returns the verified ArtifactResponse instance.
*
* @throws \Exception When unsigned, when metadata has no signing keys, or when verification fails.
*/
private function verifyArtifactResponseSignature(
ArtifactResponse $artifactResponse,
Configuration $idpMetadata,
): ArtifactResponse {
if ($artifactResponse->isSigned() !== true) {
throw new Exception('ArtifactResponse must be signed.');
}
$keys = $idpMetadata->getPublicKeys('signing', true);
if (empty($keys)) {
throw new Exception('No signing keys found in IdP metadata.');
}
$signatureMethod = $artifactResponse
->getSignature()
->getSignedInfo()
->getSignatureMethod()
->getAlgorithm()
->getValue();
$factory = new SignatureAlgorithmFactory();
$lastException = null;
foreach ($keys as $k) {
if (($k['type'] ?? null) !== 'X509Certificate') {
continue;
}
$pemCert = "-----BEGIN CERTIFICATE-----\n" .
chunk_split($k['X509Certificate'], 64) .
"-----END CERTIFICATE-----\n";
$opensslKey = openssl_pkey_get_public($pemCert);
if ($opensslKey === false) {
$lastException = new Exception('Unable to extract public key from X509 certificate.');
continue;
}
$keyInfo = openssl_pkey_get_details($opensslKey);
if ($keyInfo === false || !isset($keyInfo['key']) || !is_string($keyInfo['key'])) {
$lastException = new Exception('Unable to get public key details from X509 certificate.');
continue;
}
$pemPublicKey = $keyInfo['key'];
$file = Utils::getContainer()->getTempDir() . '/' . sha1($pemPublicKey) . '.pem';
if (!file_exists($file)) {
Utils::getContainer()->writeFile($file, $pemPublicKey);
}
try {
$verifier = $factory->getAlgorithm($signatureMethod, PublicKey::fromFile($file));
return $artifactResponse->verify($verifier);
} catch (Exception $e) {
$lastException = $e;
}
}
throw $lastException ?? new Exception('Unable to verify ArtifactResponse signature.');
}
}